/*
 * Copyright© 2003-2019 浙江汇信科技有限公司, All Rights Reserved.
 */
package com.icinfo.cloud.provider.punish.ucase.casemain.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.codec.Base64;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpStatus;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.icinfo.cloud.common.core.config.CfRedisRepository;
import com.icinfo.cloud.common.security.util.UserUtil;
import com.icinfo.cloud.provider.common.annotation.CaseChangeReportData;
import com.icinfo.cloud.provider.common.config.RedisUtil;
import com.icinfo.cloud.provider.common.constant.Constant;
import com.icinfo.cloud.provider.common.enums.*;
import com.icinfo.cloud.provider.common.exception.BusinessException;
import com.icinfo.cloud.provider.common.utils.BaseUtil;
import com.icinfo.cloud.provider.common.utils.BusinessContextUtil;
import com.icinfo.cloud.provider.common.utils.CustomCheckParamUtil;
import com.icinfo.cloud.provider.common.utils.DateUtil;
import com.icinfo.cloud.provider.peripheralinterface.xzzf.service.IXzzfInterfaceService;
import com.icinfo.cloud.provider.peripheralinterface.xzzf.vo.ZfAndManageUserInfoVO;
import com.icinfo.cloud.provider.punish.app.mapper.AppCaseBeforeDocumentRecordMapper;
import com.icinfo.cloud.provider.punish.approval.constant.AuditStatusConstant;
import com.icinfo.cloud.provider.punish.approval.mapper.CaseApprovalCompleteRecordMapper;
import com.icinfo.cloud.provider.punish.approval.mapper.CaseApprovalWaitRecordMapper;
import com.icinfo.cloud.provider.punish.approval.model.CaseApprovalCompleteRecord;
import com.icinfo.cloud.provider.punish.approval.model.CaseApprovalWaitRecord;
import com.icinfo.cloud.provider.punish.approval.service.impl.CaseApprovalWaitRecordServiceImpl;
import com.icinfo.cloud.provider.punish.common.csourcedocumentoperate.dto.CSourceDocCommonOperateSaveDto;
import com.icinfo.cloud.provider.punish.common.csourcedocumentoperate.service.ICSourceDocCommonOperateService;
import com.icinfo.cloud.provider.punish.common.documentdataload.dto.CaseDocumentRecordCommonQueryDto;
import com.icinfo.cloud.provider.punish.common.documentdataload.dto.CaseDocumentSingleRecordVo;
import com.icinfo.cloud.provider.punish.common.documentoperate.dto.*;
import com.icinfo.cloud.provider.punish.common.documentoperate.enums.DocumentLinkObjectTypeEnum;
import com.icinfo.cloud.provider.punish.common.documentoperate.enums.DocumentRecordStatusEnum;
import com.icinfo.cloud.provider.punish.common.documentoperate.enums.DocumentStatusEnum;
import com.icinfo.cloud.provider.punish.common.documentoperate.service.IStageDocCommonOperateService;
import com.icinfo.cloud.provider.punish.common.documentoperate.vo.DocumentCommonFormDataVo;
import com.icinfo.cloud.provider.punish.common.electricsent.dto.SentFlowRollInfoSaveDto;
import com.icinfo.cloud.provider.punish.common.electricsent.enums.DocumentSendStatusEnum;
import com.icinfo.cloud.provider.punish.common.electricsent.service.IDocumentSendRecordService;
import com.icinfo.cloud.provider.punish.common.electricsent.service.impl.DocumentSentFlowServiceImpl;
import com.icinfo.cloud.provider.punish.common.publicity.service.ICasePublicityModifyRecordService;
import com.icinfo.cloud.provider.punish.common.seal.dto.FileSealInfoQueryDto;
import com.icinfo.cloud.provider.punish.common.sign.dto.*;
import com.icinfo.cloud.provider.punish.common.sign.service.IFaduSignService;
import com.icinfo.cloud.provider.punish.common.sign.vo.SignSendFileVo;
import com.icinfo.cloud.provider.punish.config.dto.ConfigEndDayQueryDto;
import com.icinfo.cloud.provider.punish.config.mapper.ConfigBusiParamDocumentColumnMapper;
import com.icinfo.cloud.provider.punish.config.mapper.ConfigBusiParamDocumentInfoMapper;
import com.icinfo.cloud.provider.punish.config.model.ConfigBusiParamDocumentColumn;
import com.icinfo.cloud.provider.punish.config.model.ConfigBusiParamDocumentInfo;
import com.icinfo.cloud.provider.punish.config.service.IConfigBusiParamDocumentInfoService;
import com.icinfo.cloud.provider.punish.config.service.IConfigWorkRestDayInfoService;
import com.icinfo.cloud.provider.punish.config.vo.BusiTableOperateVo;
import com.icinfo.cloud.provider.punish.csource.manage.mapper.CaseSourceDocumentRecordMapper;
import com.icinfo.cloud.provider.punish.csource.manage.model.CaseSourceDocumentRecord;
import com.icinfo.cloud.provider.punish.csource.manage.service.ICaseSourceDocumentRecordService;
import com.icinfo.cloud.provider.punish.dataprocessing.model.DataProcessCaseMainInfoDelRecord;
import com.icinfo.cloud.provider.punish.dataprocessing.service.IDataProcessCaseMainInfoDelRecordService;
import com.icinfo.cloud.provider.punish.execute.dto.ExecuteDocCommonOperateSaveDto;
import com.icinfo.cloud.provider.punish.execute.dto.SignExecuteQueryDto;
import com.icinfo.cloud.provider.punish.execute.model.ExecuteDocumentRecord;
import com.icinfo.cloud.provider.punish.execute.service.IExecuteDocCommonOperateService;
import com.icinfo.cloud.provider.punish.execute.service.IExecuteDocumentRecordService;
import com.icinfo.cloud.provider.punish.ucase.casemain.dto.*;
import com.icinfo.cloud.provider.punish.ucase.casemain.enums.CaseStageEnum;
import com.icinfo.cloud.provider.punish.ucase.casemain.enums.HandleTypeEnum;
import com.icinfo.cloud.provider.punish.ucase.casemain.enums.PartiesReasonTypeEnum;
import com.icinfo.cloud.provider.punish.ucase.casemain.mapper.*;
import com.icinfo.cloud.provider.punish.ucase.casemain.model.*;
import com.icinfo.cloud.provider.punish.ucase.casemain.service.*;
import com.icinfo.cloud.provider.punish.ucase.casemain.vo.*;
import com.icinfo.cloud.provider.punish.ucase.caseregister.dto.CaseRegisterSaveDto;
import com.icinfo.cloud.provider.punish.ucase.caseregister.service.ICaseRegisterService;
import com.icinfo.cloud.provider.punish.ucase.investigateevidence.enums.CaseStatusChangeTypeEnum;
import com.icinfo.cloud.provider.punish.ucase.investigateevidence.mapper.CaseDocumentAuthedEntrustMapper;
import com.icinfo.cloud.provider.punish.ucase.investigateevidence.mapper.CaseDocumentSendinfoConfirmMapper;
import com.icinfo.cloud.provider.punish.ucase.investigateevidence.model.CaseDocumentAuthedEntrust;
import com.icinfo.cloud.provider.punish.ucase.investigateevidence.model.CaseDocumentSendinfoConfirm;
import com.icinfo.cloud.provider.punish.ucase.payment.mapper.CasePaymentMainRecordMapper;
import com.icinfo.cloud.provider.punish.ucase.payment.mapper.CasePaymentResultRecordMapper;
import com.icinfo.cloud.provider.punish.ucase.payment.model.CasePaymentMainRecord;
import com.icinfo.cloud.provider.punish.ucase.payment.model.CasePaymentResultRecord;
import com.icinfo.cloud.provider.punish.ucase.punishdecide.vo.CaseDecideInfoVo;
import com.icinfo.cloud.provider.punish.ucase.punishexecute.dto.DocumentOfUnExecuteQueryDto;
import com.icinfo.cloud.provider.punish.ucase.punishinform.vo.CaseCriminalTransferFileVo;
import com.icinfo.cloud.workflow.common.annotation.WorkFlowRollAnnotation;
import com.icinfo.cloud.workflow.config.model.ConfigWorkFlowDetailInfo;
import com.icinfo.cloud.workflow.config.model.ConfigWorkFlowDocument;
import com.icinfo.cloud.workflow.config.model.ConfigWorkFlowOperateDetailInfo;
import com.icinfo.cloud.workflow.config.service.IConfigWorkFlowDetailInfoService;
import com.icinfo.cloud.workflow.config.service.IConfigWorkFlowDocumentService;
import com.icinfo.cloud.workflow.config.service.IConfigWorkFlowOperateDetailInfoService;
import com.icinfo.cloud.xzcf.provider.member.userinfo.dto.UserDTO;
import com.icinfo.framework.common.web.Result;
import com.icinfo.framework.core.service.support.MyBatisServiceSupport;
import com.icinfo.framework.mybatis.mapper.entity.Example;
import com.icinfo.framework.mybatis.pagehelper.PageHelper;
import com.icinfo.framework.tools.utils.MapUtils;
import com.icinfo.framework.tools.utils.StringUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.ObjectUtils;

import javax.annotation.Resource;
import java.io.InputStream;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 描述: 案件文书记录表-TRJ case_document_record 对应的Service接口实现类.<br>
 *
 * @author framework generator
 * @date 2022年02月15日
 */
@Service
@Slf4j
@Transactional(rollbackFor = {Error.class, Exception.class})
public class CaseDocumentRecordServiceImpl extends MyBatisServiceSupport implements ICaseDocumentRecordService {

    @Resource
    private CaseDocumentRecordMapper caseDocumentRecordMapper;
    @Resource
    private CaseDocumentRecordHisMapper caseDocumentRecordHisMapper;
    @Resource
    private IConfigBusiParamDocumentInfoService configBusiParamDocumentInfoService;

    @Resource
    IStageDocCommonOperateService stageDocCommonOperateService;
    @Resource
    private ICaseDocumentRecordService caseDocumentRecordService;
    @Resource
    private ICaseAppendixRecordService caseAppendixRecordService;
    @Resource
    private IConfigWorkRestDayInfoService configWorkRestDayInfoService;
    @Resource
    private ICaseTemporaryRecordService caseTemporaryRecordService;
    @Resource
    private ICaseMainInfoService caseMainInfoService;
    @Resource
    private ICasePartiesRecordService casePartiesRecordService;
    @Resource
    private ICaseMainDetailAuxiliaryInfoService caseMainDetailAuxiliaryInfoService;
    @Autowired
    private ICaseMainDetailInfoService caseMainDetailInfoService;
    @Resource
    private ICaseMainInfoStatusChangeRecordService caseMainInfoStatusChangeRecordService;
    @Resource
    private CaseDocumentSendinfoConfirmMapper caseDocumentSendinfoConfirmMapper;
    @Autowired
    private IDocumentSendRecordService documentSendRecordService;
    @Autowired
    private IConfigWorkFlowDocumentService configWorkFlowDocumentService;
    @Autowired
    private ICaseSourceDocumentRecordService caseSourceDocumentRecordService;
    @Resource
    private ICSourceDocCommonOperateService cSourceDocCommonOperateService;
    @Resource
    private IExecuteDocCommonOperateService executeDocCommonOperateService;
    @Resource
    private CaseSourceDocumentRecordMapper caseSourceDocumentRecordMapper;
    @Resource
    private CaseMainInfoMapper caseMainInfoMapper;
    @Resource
    private CaseDocumentAuthedEntrustMapper caseDocumentAuthedEntrustMapper;
    @Resource
    private IExecuteDocumentRecordService executeDocumentRecordService;
    @Resource
    private ICasePublicityModifyRecordService casePublicityModifyRecordService;
    @Resource
    private IFaduSignService faduSignService;
    @Resource
    private CasePartiesLegalInfoMapper casePartiesLegalInfoMapper;
    @Resource
    private CasePaymentMainRecordMapper casePaymentMainRecordMapper;
    @Resource
    private CasePaymentResultRecordMapper casePaymentResultRecordMapper;
    @Resource
    private DocumentSentFlowServiceImpl documentSentFlowService;
    @Resource
    private CfRedisRepository cfRedisRepository;
    @Resource
    private CaseHandlePersonRecordServiceImpl caseHandlePersonRecordService;
    @Resource
    private CaseApprovalWaitRecordServiceImpl caseApprovalWaitRecordService;
    @Resource
    private ICaseDocumentModifyRecordService caseDocumentModifyRecordService;
    @Resource
    private ConfigBusiParamDocumentColumnMapper configBusiParamDocumentColumnMapper;
    @Resource
    private CaseDocumentModifyRecordMapper caseDocumentModifyRecordMapper;
    @Resource
    private CaseApprovalCompleteRecordMapper caseApprovalCompleteRecordMapper;
    @Resource
    private ICaseRegisterService caseRegisterService;
    @Resource
    private IXzzfInterfaceService xzzfInterfaceService;
    @Resource
    private CaseApprovalWaitRecordMapper caseApprovalWaitRecordMapper;
    @Resource
    private IConfigWorkFlowDetailInfoService configWorkFlowDetailInfoService;
    @Resource
    private ConfigBusiParamDocumentInfoMapper configBusiParamDocumentInfoMapper;
    @Resource
    private IConfigWorkFlowOperateDetailInfoService configWorkFlowOperateDetailInfoService;
    @Value("${payment.url}")
    private String paymentUrl;
    @Value("${payment.id}")
    private String paymentId;
    @Value("${ding.sendUrl}")
    private String dingSendUrl;


    @Value("${document.url}")
    private String docServerUrl;

    @Value("${document.api.uploadBase64File}")
    private String uploadBase64File;
    /**
     * 送达关联且需要当事人id的文书种类编码列表
     */
    public static List<String> sentRelatedNeedPartyIdDocumentKindCodeList;

    @Value("${dataReport.stageSwitch}")
    private String dataReportStageSwitch;
    @Resource
    private IDataProcessCaseMainInfoDelRecordService mainInfoDelRecordService;

    @Resource
    private AppCaseBeforeDocumentRecordMapper appCaseBeforeDocumentRecordMapper;

    static {
        sentRelatedNeedPartyIdDocumentKindCodeList = new ArrayList<>();
        sentRelatedNeedPartyIdDocumentKindCodeList.add(Constant.STRING_KIND_CODE_SDHZ);
        sentRelatedNeedPartyIdDocumentKindCodeList.add(Constant.STRING_KIND_CODE_ZXQKHCJL);
        sentRelatedNeedPartyIdDocumentKindCodeList.add(Constant.STRING_KIND_CODE_XWTZS);
        sentRelatedNeedPartyIdDocumentKindCodeList.add(Constant.STRING_KIND_CODE_SQWTS);
        sentRelatedNeedPartyIdDocumentKindCodeList.add(Constant.STRING_KIND_CODE_SDDZQRS);
    }

    /**
     * 【V1.0.0】描述：查询案件阶段环节关联文书信息
     *
     * @param queryDto {@link CaseStageLinkRelateDocumentQueryDto}
     * @return {@link List < CaseStageLinkRelateDocumentVo >} 案件阶段环节关联文书信息
     * @author xiangyuyu
     * @date 2022-02-24 14:29
     */
    @Override
    public List<CaseStageLinkRelateDocumentVo> getCaseStageLinkRelateDocumentInfo(CaseStageLinkRelateDocumentQueryDto queryDto) {
        List<CaseStageLinkRelateDocumentVo> caseStageLinkRelateDocumentList
                = caseDocumentRecordMapper.selectCaseStageLinkRelateDocumentInfo(queryDto);

        Set<String> set = new HashSet<>();
        Iterator<CaseStageLinkRelateDocumentVo> iterator = caseStageLinkRelateDocumentList.iterator();
        while (iterator.hasNext()) {
            CaseStageLinkRelateDocumentVo e = iterator.next();
            //非草稿状态的文书设置相关状态的名称
            if (!DocumentRecordStatusEnum.DRAFT.getCode().equals(e.getDocumentRecordStatus())) {
                e.setDocumentApprovalStatusName(DocumentStatusEnum.getValueByCode(e.getDocumentApprovalStatus()));
                e.setDocumentSentStatusName(DocumentStatusEnum.getValueByCode(e.getDocumentSentStatus()));
                e.setDocumentSignstampedStatusName(DocumentStatusEnum.getValueByCode(e.getDocumentSignstampedStatus()));
            }
            e.setDocumentRecordStatusName(DocumentRecordStatusEnum.getValueByCode(e.getDocumentRecordStatus()));
            //update
            if (StringUtils.isNotEmpty(e.getDocumentUrlAfterSeal())) {
                e.setDocumentUrl(e.getDocumentUrlAfterSeal());
            }
            if (StringUtils.isNotEmpty(e.getDocumentUrlAfterSign())) {
                e.setDocumentUrl(e.getDocumentUrlAfterSign());
            }
            String documentKindCode = e.getDocumentKindCode();
            if (Constant.STRING_KIND_CODE_ZXQKHCJL.equals(documentKindCode)) {
                String kindCode = e.getDocumentKindCode();
                String partyId = e.getPartyId();
                String combineInfo = kindCode + "_" + partyId;
                if (set.contains(combineInfo)) {
                    iterator.remove();
                } else {
                    set.add(combineInfo);
                }
            }
        }
        return caseStageLinkRelateDocumentList;
    }

    /**
     * 【V1.0.0】描述：根据唯一标识查询文书记录信息
     *
     * @param id 唯一标识
     * @return {@link CaseDocumentRecordVo} 文书记录信息
     * @author xiangyuyu
     * @date 2022-02-25 14:28
     */
    @Override
    public CaseDocumentRecordVo getCaseDocumentRecordInfo(String id) {
        CaseDocumentRecord caseDocumentRecord = caseDocumentRecordMapper.selectByPrimaryKey(id);
        if (ObjectUtils.isEmpty(caseDocumentRecord)) {
            throw new BusinessException("未匹配到文书记录");
        }
        CaseDocumentRecordVo vo = new CaseDocumentRecordVo();
        BeanUtils.copyProperties(caseDocumentRecord, vo);
        return vo;
    }

    @Override
    public SignSendFileVo getUnSignDoc(SignQueryDto signQueryDto) {
        SignSendFileVo vo = new SignSendFileVo();
        String documentCatalogCode = signQueryDto.getDocCategoryCode();
        String caseId = signQueryDto.getCaseId();
        //增加送达当事人id处理
        if (ObjectUtils.isEmpty(signQueryDto.getPartyId())) {
            CaseMainInfoVo caseMainInfo = caseMainInfoService.getCaseMainInfo(caseId);
            String casePartiesReasonType = caseMainInfo.getCasePartiesReasonType();
            // FIXME: 2022/8/3
            //查询文书种类
            List<ConfigBusiParamDocumentInfo> configList = configBusiParamDocumentInfoService.getDocumentConfigInfoByDocumentCatalogCode(caseId, caseMainInfo, documentCatalogCode);
            String kindCode;
            if (!ObjectUtils.isEmpty(configList)) {
                kindCode = configList.get(Constant.INTEGER_0).getDocumentKindCode();
            } else {
                throw new BusinessException("未匹配文书种类编码信息-caseId:" + caseId + ",documentCatalogCode:" + documentCatalogCode);
            }
            if (PartiesReasonTypeEnum.MULTIPLE_PARTIES.getCode().equals(casePartiesReasonType)
                    && !Constant.STRING_KIND_CODE_GZSHZ.equals(kindCode)) {
                throw new BusinessException("多当事人案件需指定当事人id");
            }
            Map<String, String> map = casePartiesRecordService.getCasePartyIdNameInfo(signQueryDto.getCaseId());
            String partyId = map.get("partyId");
            signQueryDto.setPartyId(partyId);
        }
        String partyId = signQueryDto.getPartyId();
        CaseDocumentRecord caseDocumentRecord = caseDocumentRecordService.getCaseDocumentRecord(caseId, documentCatalogCode, partyId);
        vo.setCaseId(signQueryDto.getCaseId());
        vo.setDocCategoryCode(signQueryDto.getDocCategoryCode());
        vo.setPartyId(signQueryDto.getPartyId());
        if (caseDocumentRecord != null) {
            // 重新生成带签字确认日期的原文件
            StageDocCommonOperateSaveDto saveDto = new StageDocCommonOperateSaveDto();
            saveDto.setCaseId(signQueryDto.getCaseId());
            saveDto.setDocumentCatalogCode(signQueryDto.getDocCategoryCode());
            saveDto.setPartyId(signQueryDto.getPartyId());
            JSONObject jsonObject = JSON.parseObject(caseDocumentRecord.getDocumentContent());
            HashMap<String, Object> jsonMap = new HashMap<>(16);
            for (Map.Entry<String, Object> entry : jsonObject.entrySet()) {
                jsonMap.put(entry.getKey(), entry.getValue());
            }
            jsonMap.put("signTime", LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy年M月d日")));
            saveDto.setDataMap(jsonMap);
            saveDto.setIsUpdateRelationTable(Constant.STRING_0);

            //根据文书目录编码获取模板code
            String templateCode = stageDocCommonOperateService.getTemplateCodeByDocumentCatalogCode(saveDto.getDocumentCatalogCode(), caseId, saveDto.getDataMap(), partyId);
            //处理参数
            saveDto.setDocumentTemplateCode(templateCode);
            FillAndConvertToPdfRequest pdfRequest = new FillAndConvertToPdfRequest();
            pdfRequest.setTemplateCode(templateCode);
            pdfRequest.setParamMap(saveDto.getDataMap());
            //判断文书模板类型是否为窄幅
            if (DocumentTemplateTypeEnum.NARROW_TEMPLATE.getCode().equals(saveDto.getDocumentTemplateType())) {
                pdfRequest.setTemplateType(DocumentTemplateKindEnum.NARROW_TEMPLATE.getCode());
            }
            // 重新生成文书
            Map<String, String> pdfUrl = stageDocCommonOperateService.getConvertedPdfUrl(pdfRequest);
            if (ObjectUtil.isEmpty(pdfUrl)) {
                throw new BusinessException("获取文书失败！");
            }
            vo.setDocStr(pdfUrl.get("fileBase64"));
            //已签章地址处理
            if (ObjectUtil.isNotEmpty(caseDocumentRecord.getDocumentUrlAfterSeal())) {
                FileSealInfoQueryDto queryDto = new FileSealInfoQueryDto();
                queryDto.setFileBase64(pdfUrl.get("fileBase64"));
                String relatePdfSealUrl = stageDocCommonOperateService.dealFileSeal(queryDto);
                InputStream is = HttpUtil.createGet(relatePdfSealUrl).execute().bodyStream();
                vo.setDocStr(Base64.encode(is));
            }


            // 重新生成文书
            /*Map<String, Object> resultMap = stageDocCommonOperateService.saveDocInfo(saveDto);
            String st = "true";
            String success = "success";
            if (!st.equals(resultMap.get(success).toString())) {
                throw new BusinessException("获取文书失败！");
            }
            // 生成后重新查询
            caseDocumentRecord = caseDocumentRecordService.getCaseDocumentRecord(caseId, documentCatalogCode, partyId);
            InputStream is = null;
            if (StringUtils.isNotBlank(caseDocumentRecord.getDocumentUrlAfterSeal())) {
                is = HttpUtil.createGet(caseDocumentRecord.getDocumentUrlAfterSeal()).execute().bodyStream();
            } else {
                is = HttpUtil.createGet(caseDocumentRecord.getDocumentUrl()).execute().bodyStream();
            }
            // 文件转为base64
            vo.setDocStr(Base64.encode(is));*/
        } else {
            log.error("未匹配到文书记录-getUnSignDoc,caseId:{},partyId:{},documentCatalogCode:{}", caseId, partyId, documentCatalogCode);
            throw new BusinessException("未匹配到文书记录-getUnSignDoc");
        }
        return vo;
    }

    @Override
    @WorkFlowRollAnnotation
    @CaseChangeReportData
    @Transactional(rollbackFor = Exception.class)
    public Map<String, Object> receiveSignDoc(SignReturnDto signReceiveDto) {
        log.info("receiveSignDoc start... signReceiveDto:{}", signReceiveDto);
        if (ObjectUtils.isEmpty(signReceiveDto)) {
            throw new BusinessException("未指定文书案件相关信息");
        }
        String caseId = signReceiveDto.getCaseId();
        if (ObjectUtils.isEmpty(caseId)) {
            throw new BusinessException("未指定案件id");
        }
        String docCategoryCode = signReceiveDto.getDocCategoryCode();
        if (ObjectUtils.isEmpty(docCategoryCode)) {
            throw new BusinessException("未指定文书目录编码");
        }
        String partyId = signReceiveDto.getPartyId();
        String documentCatalogCode = signReceiveDto.getDocCategoryCode();
        CaseMainInfoVo caseMainInfo = caseMainInfoService.getCaseMainInfo(caseId);
        String partiesReasonType = caseMainInfo.getCasePartiesReasonType();
        String handleType = caseMainInfo.getHandleType();

        //查询文书种类
        List<ConfigBusiParamDocumentInfo> configList = configBusiParamDocumentInfoService.getDocumentConfigInfoByDocumentCatalogCode(caseId, caseMainInfo, documentCatalogCode);
        String kindCode;
        if (!ObjectUtils.isEmpty(configList)) {
            kindCode = configList.get(Constant.INTEGER_0).getDocumentKindCode();
        } else {
            throw new BusinessException("未匹配文书种类编码信息-caseId:" + caseId + ",documentCatalogCode:" + documentCatalogCode);
        }
        //增加送达当事人id处理
        if (ObjectUtils.isEmpty(partyId)) {
            if (PartiesReasonTypeEnum.MULTIPLE_PARTIES.getCode().equals(partiesReasonType)
                    && !"GZSHZ".equals(kindCode)
            ) {
                throw new BusinessException("多当事人案件需指定当事人id");
            }
            Map<String, String> map = casePartiesRecordService.getCasePartyIdNameInfo(caseId);
            partyId = map.get("partyId");
        }
        //如果传的文书记录ID不为空，则需要根据文书记录ID去查询
        CaseDocumentRecord caseDocumentRecordUpdate = null;
        if (StrUtil.isNotEmpty(signReceiveDto.getDocumentRecordId())) {
            caseDocumentRecordUpdate = caseDocumentRecordMapper.selectByPrimaryKey(signReceiveDto.getDocumentRecordId());
        } else {
            caseDocumentRecordUpdate = getCaseDocumentRecord(caseId, docCategoryCode, partyId);
        }
        if (caseDocumentRecordUpdate == null) {
            log.error("未匹配到文书记录-receiveSignDoc,caseId:{},partyId:{},documentCatalogCode:{}", caseId, partyId, documentCatalogCode);
            throw new BusinessException("未匹配到文书记录-receiveSignDoc");
        }
        // 签字捺印保存requestId,signDeviceType到content 里
        String documentContent = caseDocumentRecordUpdate.getDocumentContent();
        JSONObject documentContentJson = JSON.parseObject(documentContent);
        documentContentJson.put("requestId", signReceiveDto.getRequestId());
        documentContentJson.put("signDeviceType", signReceiveDto.getSignDeviceType());
        caseDocumentRecordUpdate.setDocumentContent(documentContentJson.toJSONString());
        caseDocumentRecordUpdate.setSignTime(LocalDateTime.now());

        // 保存法度签字捺印视频和文件
        if (Constant.STRING_2.equals(signReceiveDto.getSignDeviceType())) {
            try {
                FaduSignAttachmentFileSaveDto attachmentFileSaveDto = new FaduSignAttachmentFileSaveDto();
                attachmentFileSaveDto.setWorkId(signReceiveDto.getCaseId());
                attachmentFileSaveDto.setBusinessType(Constant.STRING_1);
                attachmentFileSaveDto.setDocCategoryCode(signReceiveDto.getDocCategoryCode());
                attachmentFileSaveDto.setPartyId(partyId);
                faduSignService.saveSignZip(attachmentFileSaveDto, signReceiveDto.getRequestId());
            } catch (Exception e) {
                e.printStackTrace();
                log.info("=======法度签字捺印视频和文件失败，workId:{},docCategoryCode:{},requestId:{},message:{}", signReceiveDto.getCaseId(), docCategoryCode, signReceiveDto.getRequestId(), e.getMessage());
            }
        }

        String signDocumentUrl = "";
        //海康的设备直接获取签字后地址
        if (Constant.STRING_1.equals(signReceiveDto.getSignDeviceType()) && ObjectUtil.isNotEmpty(signReceiveDto.getSignDocUrl())) {
            signDocumentUrl = signReceiveDto.getSignDocUrl();
        } else {
            //其他设备
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("fileBase64", signReceiveDto.getDocStr());
            jsonObject.put("fileType", "pdf");
            jsonObject.put("fileName", "");
            JSONObject parseObject = JSON.parseObject(HttpUtil.post(docServerUrl + uploadBase64File, jsonObject.toString()));
            String cd = "code";
            int th = 200;
            if (parseObject.getInteger(cd) == th) {
                signDocumentUrl = parseObject.getJSONObject("data").getString("ossUrl");

                log.info("receiveSignDoc doc url:{}", signDocumentUrl);
            } else {
                log.info("warn receive sign file upload oss fail,result:{}", parseObject.toString());
                throw new BusinessException("文件上传时出现异常-receiveSignDoc");
            }
        }
        caseDocumentRecordUpdate.setDocumentUrlAfterSign(signDocumentUrl);
        caseDocumentRecordUpdate.setDocumentSignstampedStatus(DocumentStatusEnum.CONFIRM_END.getCode());
        //当文书为送达方式及地址确认书更新文书创建时间作为确认时间来使用,后续用于计算有效期限
        ConfigBusiParamDocumentInfo configBusiParamDocumentInfo = configBusiParamDocumentInfoService.getDetailByDocumentCatalogCode(docCategoryCode);
        if (Constant.STRING_KIND_CODE_SDDZQRS.equals(configBusiParamDocumentInfo.getDocumentKindCode())) {
            caseDocumentRecordUpdate.setDocumentCreateTime(LocalDateTime.now());
            //送达地址确认书确认时更新送达地址确认书表的状态为1
            Example updateExample = new Example(CaseDocumentSendinfoConfirm.class);
            updateExample.createCriteria().andEqualTo("caseId", caseDocumentRecordUpdate.getCaseId()).andEqualTo("partyId", caseDocumentRecordUpdate.getPartyId());
            CaseDocumentSendinfoConfirm caseDocumentSendinfoConfirm = new CaseDocumentSendinfoConfirm();
            caseDocumentSendinfoConfirm.setStatus(Constant.INTEGER_1);
            caseDocumentSendinfoConfirmMapper.updateByExampleSelective(caseDocumentSendinfoConfirm, updateExample);
        }
        // 签字之后判断案件是否需要，更新案件状态,查询配置表
        // todo
        Map<String, Object> rs = new HashMap<>(8);
        if (this.caseDocumentRecordMapper.updateByPrimaryKeySelective(caseDocumentRecordUpdate) == 1) {
            rs.put("workId", caseId);
            rs.put("closeSignal", "CLOSE-TRIGGER-SIGNSTAMPED");
            if (!ObjectUtils.isEmpty(partyId)) {
                if (!ObjectUtils.isEmpty(configList)) {
                    if (sentRelatedNeedPartyIdDocumentKindCodeList.contains(kindCode)) {
                        rs.put("workSubId", partyId);
                    }
                }
                if (Constant.STRING_2.equals(handleType)) {
                    rs.put("workSubId", partyId);
                } else {
                    rs.put("workSubId", null);
                }
            }
            if (!ObjectUtils.isEmpty(documentCatalogCode) && documentCatalogCode.contains(Constant.STRING_UNDERLINE)) {
                /*if (documentCatalogCode.contains("SDHZBD1F5")) {
                    kindCode = Constant.STRING_KIND_CODE_CFGZS;
                } else if (documentCatalogCode.contains("SDHZBD1F6")) {
                    kindCode = Constant.STRING_KIND_CODE_CFGZSTZL;
                } else if (documentCatalogCode.contains("SDHZBD1F7")) {
                    //判断是否为简易处罚
                    kindCode = Constant.STRING_KIND_CODE_CFJDS;
                    if (CaseTypeEnum.SIMPLE_PROCEDURE.getCode().equals(caseMainInfo.getCaseType())) {
                        kindCode = Constant.STRING_KIND_CODE_JYCXCFJDS;
                    }
                } else if (documentCatalogCode.contains("SDHZ7B444")) {
                    kindCode = Constant.STRING_KIND_CODE_BYCFJDS;
                } else if (documentCatalogCode.contains("SDHZC8650")) {
                    kindCode = Constant.STRING_KIND_CODE_JDYJGZS;
                } else if (documentCatalogCode.contains("SDHZBD1F8")) {
                    kindCode = Constant.STRING_KIND_CODE_XZCFCXJDS;
                } else if (documentCatalogCode.contains("SDHZBD3FG")) {
                    kindCode = Constant.STRING_KIND_CODE_XZJDLXCGS;
                } else {
                    throw new BusinessException("未找到对应更新文书目录编码-receiveSignDoc");
                }
                List<ConfigBusiParamDocumentInfo> list = configBusiParamDocumentInfoService.getDocumentConfigInfoByDocumentKindCode(caseId,caseMainInfo,kindCode);
                if(!ObjectUtils.isEmpty(list)){
                    documentCatalogCode = list.get(Constant.INTEGER_0).getDocumentCatalogCode();
                } else {
                    throw new BusinessException("未匹配文书目录编码信息-caseId:" + caseId + ",kindCode:" + kindCode);
                }*/

                //查询送达回证配置
                ConfigBusiParamDocumentInfo detailByDocumentCatalogCode = configBusiParamDocumentInfoService.getDetailByDocumentCatalogCode(documentCatalogCode);
                documentCatalogCode = detailByDocumentCatalogCode.getMatchSentDocumentCatalogCode();
                if (ObjectUtils.isEmpty(documentCatalogCode)) {
                    throw new BusinessException("未找到对应更新文书目录编码-receiveSignDoc");
                }

                //更新文书送达时间
                String sendStatus = DocumentSendStatusEnum.SEND_SUCCESS.getCode();
                CaseDocumentRecordQueryDto queryDto = new CaseDocumentRecordQueryDto();
                queryDto.setCaseId(caseId);
                queryDto.setRelateDocumentCatalogCode(documentCatalogCode);
                if (!HandleTypeEnum.MERGE_PUNISH.getCode().equals(handleType)) {
                    queryDto.setPartyId(partyId);
                }
                CaseDocumentRecordDetailVo vo = getCaseDocumentRecordDetail(queryDto);
                if (ObjectUtils.isEmpty(vo)) {
                    throw new BusinessException("未找到文书记录-caseId:{" + caseId + "},documentCatalogCode:{" + documentCatalogCode + "}");
                }
                rs.put("closeSignal", "CLOSE-TRIGGER-SENT");
                String documentId = vo.getDocumentId();
                if (documentSentFlowService.checkDocumentIsAllSend(caseId, documentId)) {
                    caseDocumentRecordService.updateDocumentSentInfo(documentId, LocalDateTime.now(), sendStatus);
                }
                //caseDocumentRecordService.updateDocumentSentInfo(vo.getDocumentId(), LocalDateTime.now(), sendStatus);
            } else {
                List<String> list = new ArrayList<>();
                list.add("CFGZS");
                list.add("CFGZSTZL");
                list.add("CFJDS");
                list.add("BYCFJDS");
                if (list.contains(kindCode)) {
                    //取对应审批表
                    rs.put("closeSignal", "CLOSE-TRIGGER-SENT");
                }
            }
            rs.put("documentCatalogCode", documentCatalogCode);
        } else {
            throw new BusinessException("更新文书信息时出现异常");
        }
        return rs;
    }

    @WorkFlowRollAnnotation
    @CaseChangeReportData
    @Transactional(rollbackFor = Exception.class)
    @Override
    public Map<String, Object> receiveAppSignDoc(SignReturnDto signReceiveDto) {
        // FIXME: 2022/8/2 移动端的签字捺印还没有实际测试过

        if (ObjectUtils.isEmpty(signReceiveDto)) {
            throw new BusinessException("未指定文书案件相关信息");
        }
        String caseId = signReceiveDto.getCaseId();
        String partyId = signReceiveDto.getPartyId();

        // 签字之后判断案件是否需要，更新案件状态,查询配置表
        Map<String, Object> rs = new HashMap<>(8);

        rs.put("workId", caseId);
        rs.put("closeSignal", "CLOSE-TRIGGER-SIGNSTAMPED");
        String documentCatalogCode = signReceiveDto.getDocCategoryCode();
        CaseMainInfoVo caseMainInfo = caseMainInfoService.getCaseMainInfo(caseId);
        //查询文书种类
        List<ConfigBusiParamDocumentInfo> configList = configBusiParamDocumentInfoService.getDocumentConfigInfoByDocumentCatalogCode(caseId, caseMainInfo, documentCatalogCode);
        String kindCode;
        if (!ObjectUtils.isEmpty(configList)) {
            kindCode = configList.get(Constant.INTEGER_0).getDocumentKindCode();
        } else {
            throw new BusinessException("未匹配文书种类编码信息-caseId:" + caseId + ",documentCatalogCode:" + documentCatalogCode);
        }
        String partiesReasonType = caseMainInfo.getCasePartiesReasonType();
        String handleType = caseMainInfo.getHandleType();
        //增加送达当事人id处理
        if (ObjectUtils.isEmpty(partyId)) {
            if (PartiesReasonTypeEnum.MULTIPLE_PARTIES.getCode().equals(partiesReasonType)
                    && !"GZSHZ".equals(kindCode)
            ) {
                throw new BusinessException("多当事人案件需指定当事人id");
            }
            Map<String, String> map = casePartiesRecordService.getCasePartyIdNameInfo(caseId);
            partyId = map.get("partyId");
        }
        if (!ObjectUtils.isEmpty(documentCatalogCode) && documentCatalogCode.contains(Constant.STRING_UNDERLINE)) {
            /*if (documentCatalogCode.contains("SDHZBD1F5")) {
                kindCode = Constant.STRING_KIND_CODE_CFGZS;
            } else if (documentCatalogCode.contains("SDHZBD1F6")) {
                kindCode = Constant.STRING_KIND_CODE_CFGZSTZL;
            } else if (documentCatalogCode.contains("SDHZBD1F7")) {
                //判断是否为简易处罚
                kindCode = Constant.STRING_KIND_CODE_CFJDS;
                if (CaseTypeEnum.SIMPLE_PROCEDURE.getCode().equals(caseMainInfo.getCaseType())) {
                    kindCode = Constant.STRING_KIND_CODE_JYCXCFJDS;
                }
            } else if (documentCatalogCode.contains("SDHZ7B444")) {
                kindCode = Constant.STRING_KIND_CODE_BYCFJDS;
            } else if (documentCatalogCode.contains("SDHZC8650")) {
                kindCode = Constant.STRING_KIND_CODE_JDYJGZS;
            } else if (documentCatalogCode.contains("SDHZBD1F8")) {
                kindCode = Constant.STRING_KIND_CODE_XZCFCXJDS;
            } else if (documentCatalogCode.contains("SDHZBD3FG")) {
                kindCode = Constant.STRING_KIND_CODE_XZJDLXCGS;
            } else {
                throw new BusinessException("未找到对应更新文书目录编码-receiveAppSignDoc");
            }

            List<ConfigBusiParamDocumentInfo> list = configBusiParamDocumentInfoService.getDocumentConfigInfoByDocumentKindCode(caseId,caseMainInfo,kindCode);
            if(!ObjectUtils.isEmpty(list)){
                documentCatalogCode = list.get(Constant.INTEGER_0).getDocumentCatalogCode();
            } else {
                throw new BusinessException("未匹配文书目录编码信息-caseId:" + caseId + ",kindCode:" + kindCode);
            }*/

            //查询送达回证配置
            ConfigBusiParamDocumentInfo detailByDocumentCatalogCode = configBusiParamDocumentInfoService.getDetailByDocumentCatalogCode(documentCatalogCode);
            documentCatalogCode = detailByDocumentCatalogCode.getMatchSentDocumentCatalogCode();
            if (ObjectUtils.isEmpty(documentCatalogCode)) {
                throw new BusinessException("未找到对应更新文书目录编码-receiveAppSignDoc");
            }

            //更新文书送达时间
            String sendStatus = DocumentSendStatusEnum.SEND_SUCCESS.getCode();
            CaseDocumentRecordQueryDto queryDto = new CaseDocumentRecordQueryDto();
            queryDto.setCaseId(caseId);
            queryDto.setRelateDocumentCatalogCode(documentCatalogCode);
            CaseDocumentRecordDetailVo vo = getCaseDocumentRecordDetail(queryDto);
            if (!HandleTypeEnum.MERGE_PUNISH.getCode().equals(handleType)) {
                queryDto.setPartyId(partyId);
            }
            if (ObjectUtils.isEmpty(vo)) {
                throw new BusinessException("未找到文书记录-caseId:{" + caseId + "},documentCatalogCode:{" + documentCatalogCode + "}");
            }
            rs.put("closeSignal", "CLOSE-TRIGGER-SENT");
            caseDocumentRecordService.updateDocumentSentInfo(vo.getDocumentId(), LocalDateTime.now(), sendStatus);
        } else {
            List<String> list = new ArrayList<>();
            list.add("CFGZS");
            list.add("CFGZSTZL");
            list.add("CFJDS");
            list.add("BYCFJDS");
            if (list.contains(kindCode)) {
                //取对应审批表
                rs.put("closeSignal", "CLOSE-TRIGGER-SENT");
            }
        }
        rs.put("documentCatalogCode", documentCatalogCode);

        return rs;
    }

    /**
     * 删除文书记录
     *
     * @param caseDocumentRecordDelRequest
     * @return {@link int}
     * @author liyafeng
     * @date 2022/3/1
     */
    @Override
    public int delCaseDocumentRecordInfo(CaseDocumentRecordDelRequest caseDocumentRecordDelRequest) {
        int num = 0;
        String caseId = caseDocumentRecordDelRequest.getCaseId();
        String documentCatalogCode = caseDocumentRecordDelRequest.getDocumentCatalogCode();
        String partyId = caseDocumentRecordDelRequest.getPartyId();
        CaseMainInfoVo caseMainInfo = caseMainInfoService.getCaseMainInfo(caseId);
        if (caseMainInfoService.validateCaseIsInNotDealStatus(caseMainInfo, null)) {
            throw new BusinessException("当前案件状态不允许进行该操作");
        }
        //查询关联文书
        ConfigBusiParamDocumentInfo configBusiParamDocumentInfo = configBusiParamDocumentInfoService.getDetailByDocumentCatalogCode(documentCatalogCode);
        String documentKindCode = configBusiParamDocumentInfo.getDocumentKindCode();
        //不予立案审批删除时 删除文书 删除案件
        if (Constant.KIND_CODE_DT2BYLASPB.equals(configBusiParamDocumentInfo.getDocumentKindCode())) {
            Example example = new Example(CaseDocumentRecord.class);
            example.createCriteria().andEqualTo("caseId", caseId).andEqualTo("documentCatalogCode", documentCatalogCode)
                    //.andNotEqualTo("documentRecordStatus", DocumentRecordStatusEnum.WITHDRAW.getCode());
                    .andIn("documentRecordStatus", Arrays.asList(DocumentRecordStatusEnum.NORMAL.getCode(), DocumentRecordStatusEnum.DRAFT.getCode()));
            List<CaseDocumentRecord> caseDocumentRecords = caseDocumentRecordMapper.selectByExample(example);
            //不为空，则添加历史，删除记录
            num = deleteAndSaveHis(caseDocumentRecords);
            //先删除案件删除记录
            mainInfoDelRecordService.delRecord(caseId);

            CaseMainInfo caseInfo = caseMainInfoMapper.selectByPrimaryKey(caseId);
            DataProcessCaseMainInfoDelRecord dataProcessCaseMainInfoDelRecord = BeanUtil.toBean(caseInfo, DataProcessCaseMainInfoDelRecord.class);
            dataProcessCaseMainInfoDelRecord.setCaseLinkTag("业务删除");
            mainInfoDelRecordService.saveRecord(dataProcessCaseMainInfoDelRecord);
            caseMainInfoMapper.deleteByPrimaryKey(caseId);
            return num;
        }
        //查询文书记录数据
        Example example = new Example(CaseDocumentRecord.class);
        if (ObjectUtils.isEmpty(partyId)) {
            if (caseMainInfoService.validateIsNeedPassPartyId(null, caseId)) {
                throw new BusinessException("多当事人分别处罚时请指定当事人id");
            }
            Map<String, String> map = casePartiesRecordService.getCasePartyIdNameInfo(caseId);
            partyId = map.get("partyId");
        }
        example.createCriteria().andEqualTo("caseId", caseId).andEqualTo("documentCatalogCode", documentCatalogCode).andEqualTo("partyId", partyId)
                //.andNotEqualTo("documentRecordStatus", DocumentRecordStatusEnum.WITHDRAW.getCode());
                .andIn("documentRecordStatus", Arrays.asList(DocumentRecordStatusEnum.NORMAL.getCode(), DocumentRecordStatusEnum.DRAFT.getCode()));

        List<CaseDocumentRecord> caseDocumentRecords = caseDocumentRecordMapper.selectByExample(example);
        if (null != caseDocumentRecords && caseDocumentRecords.size() > 0) {
            //不为空，则添加历史，删除记录
            num = deleteAndSaveHis(caseDocumentRecords);
            //同时删除当前环节附件
            caseAppendixRecordService.removeCaseAppendixRecordByCaseIdAndCatalogCodeAndPartyId(caseId, documentCatalogCode, partyId);

        }
        //删除暂存内容
        caseTemporaryRecordService.removeTemporary(caseId, documentCatalogCode, partyId);

        if (Constant.STRING_KIND_CODE_SQWTS.equals(configBusiParamDocumentInfo.getDocumentKindCode())) {
            //删除授权委托书信息
            Example autExample = new Example(CaseDocumentAuthedEntrust.class);
            autExample.createCriteria().andEqualTo("caseId", caseId).andEqualTo("partyId", partyId);
            caseDocumentAuthedEntrustMapper.deleteByExample(autExample);
        }

        // 删除了送达方式和地址确认书撤回所有浙里办数据
        if (Constant.STRING_KIND_CODE_SDDZQRS.equals(configBusiParamDocumentInfo.getDocumentKindCode())) {
            //删除送达方式和地址确认书信息
            Example autExample = new Example(CaseDocumentSendinfoConfirm.class);
            autExample.createCriteria().andEqualTo("caseId", caseId).andEqualTo("partyId", partyId);
            caseDocumentSendinfoConfirmMapper.deleteByExample(autExample);

            CaseDocumentRecord caseDocumentRecord = new CaseDocumentRecord();
            caseDocumentRecord.setZlbService(Constant.STRING_0);
            Example example1 = new Example(CaseDocumentRecord.class);
            Example.Criteria criteria = example1.createCriteria();
            criteria.andEqualTo("caseId", caseId);
            if (StringUtils.isNotBlank(partyId)) {
                criteria.andEqualTo("partyId", partyId);
            }
            caseDocumentRecordMapper.updateByExampleSelective(caseDocumentRecord, example1);
        }

        if (!ObjectUtils.isEmpty(caseDocumentRecordDelRequest.getDocumentId())) {
            Example docExample = new Example(CaseDocumentRecord.class);
            docExample.createCriteria().andEqualTo("id", caseDocumentRecordDelRequest.getDocumentId())
                    .andEqualTo("caseId", caseId);
            caseDocumentRecordMapper.deleteByExample(docExample);
            //案件操作文书删除
            if (CaseStatusChangeTypeEnum.isCaseChangeDocEnum(documentKindCode)) {
                caseMainInfoStatusChangeRecordService.deleteStatusChangeRecordByDocumentId(caseDocumentRecordDelRequest.getDocumentId());
            }
            //更正审批表
            if (DocumentKindEnum.DOC_KIND_DT1SQGZGSSPB.getCode().equals(documentKindCode)) {
                casePublicityModifyRecordService.removeCasePublicityModifyRecordDetailByDocumentId(caseDocumentRecordDelRequest.getDocumentId());
            }
        }

        String relateCode = configBusiParamDocumentInfo.getRelationDocumentCatalogCode();
        if (StringUtils.isNotBlank(relateCode)) {
            String[] relateCodeArr = relateCode.split(",");
            for (String relateCodeStr : relateCodeArr) {
                //删除暂存内容
                caseTemporaryRecordService.removeTemporary(caseId, relateCodeStr, partyId);
                //查询文书记录数据
                Example relateExample = new Example(CaseDocumentRecord.class);
                relateExample.createCriteria().andEqualTo("caseId", caseId).andEqualTo("documentCatalogCode", relateCodeStr).andEqualTo("partyId", partyId)
                        //.andNotEqualTo("documentRecordStatus", DocumentRecordStatusEnum.WITHDRAW.getCode());
                        .andIn("documentRecordStatus", Arrays.asList(DocumentRecordStatusEnum.NORMAL.getCode(), DocumentRecordStatusEnum.DRAFT.getCode()));
                List<CaseDocumentRecord> relateCaseDocumentRecords = caseDocumentRecordMapper.selectByExample(relateExample);
                if (null != relateCaseDocumentRecords && relateCaseDocumentRecords.size() > 0) {
                    num = deleteAndSaveHis(relateCaseDocumentRecords);
                    //同时删除当前环节附件
                    caseAppendixRecordService.removeCaseAppendixRecordByCaseIdAndCatalogCodeAndPartyId(caseDocumentRecordDelRequest.getCaseId(), relateCodeStr, partyId);
                }

            }
        }

        return num;
    }

    /**
     * 根据ID删除文书记录
     *
     * @param caseDocumentRecordDelRequest
     * @return {@link int}
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int delCaseDocumentRecordById(CaseDocumentRecordDelRequest caseDocumentRecordDelRequest) {
        int num = 0;
        String caseId = caseDocumentRecordDelRequest.getCaseId();
        CaseMainInfoVo caseMainInfo = caseMainInfoService.getCaseMainInfo(caseId);
        if (caseMainInfoService.validateCaseIsInNotDealStatus(caseMainInfo, null)) {
            throw new BusinessException("当前案件状态不允许进行该操作");
        }
        CaseDocumentRecord caseDocumentRecord = caseDocumentRecordMapper.selectByPrimaryKey(caseDocumentRecordDelRequest.getDocumentId());
        if (caseDocumentRecord == null) {
            throw new BusinessException("未找到需要删除的数据");
        }
        //如果是草稿的话，根据类型和relationDocumentId来删除
        if (DocumentRecordStatusEnum.DRAFT.getCode().equals(caseDocumentRecord.getDocumentRecordStatus())) {
            Example example = new Example(CaseDocumentRecord.class);
            example.createCriteria().andEqualTo("documentRecordStatus", DocumentRecordStatusEnum.DRAFT.getCode())
                    .andEqualTo("relationDocumentId", caseDocumentRecord.getRelationDocumentId());
            List<CaseDocumentRecord> list = caseDocumentRecordMapper.selectByExample(example);
            num = deleteAndSaveHis(list);
            return num;
        }
        //删除关联文书
        CaseDocumentRecord param = new CaseDocumentRecord();
        param.setRelationApprovalDocumentId(caseDocumentRecord.getId());
        CaseDocumentRecord caseDocumentRelationRecord = caseDocumentRecordMapper.selectOne(param);
        List<CaseDocumentRecord> list = CollUtil.toList(caseDocumentRecord, caseDocumentRelationRecord);
        num = deleteAndSaveHis(list);
        return num;
    }

    /**
     * 删除并添加历史
     *
     * @param
     * @return {@link int}
     * @author liyafeng
     * @date 2022/3/11
     */
    private int deleteAndSaveHis(List<CaseDocumentRecord> caseDocumentRecords) {
        int num = 0;
        //不为空，则添加历史，删除记录
        for (CaseDocumentRecord caseDocumentRecord : caseDocumentRecords) {
            //已审批完成的文书不删除 ,删除草稿文书
            if (DocumentRecordStatusEnum.DRAFT.getCode().equals(caseDocumentRecord.getDocumentRecordStatus())
                    || !DocumentStatusEnum.CHECK_END.getCode().equals(caseDocumentRecord.getDocumentApprovalStatus())) {
                //添加历史
                CaseDocumentRecordHis caseDocumentRecordHis = new CaseDocumentRecordHis();
                BeanUtils.copyProperties(caseDocumentRecord, caseDocumentRecordHis);
                caseDocumentRecordHis.setId(StringUtils.uuid());
                caseDocumentRecordHis.setRecordId(caseDocumentRecord.getId());
                caseDocumentRecordHis.setOp("delete");
                caseDocumentRecordHis.setHisCreateTime(new Date());
                caseDocumentRecordHisMapper.insert(caseDocumentRecordHis);
                // 删除案件操作记录
                caseMainInfoStatusChangeRecordService.deleteStatusChangeRecordByDocumentId(caseDocumentRecord.getId());
                //删除文书记录表
                num = caseDocumentRecordMapper.deleteByPrimaryKey(caseDocumentRecord.getId());
            }
        }
        return num;
    }

    /**
     * 描述：更新文书送达截止日期
     *
     * @param caseId              案件id
     * @param documentCatalogCode 文书目录编码
     * @author xiangyuyu
     * @date 2022-03-04 09:41
     */
    @Override
    public void updateDocumentSentDeadLine(String caseId, String documentCatalogCode) {
        if (ObjectUtils.isEmpty(caseId)) {
            throw new BusinessException("更新文书送达截止日期时未指定案件id");
        }
        if (ObjectUtils.isEmpty(documentCatalogCode)) {
            throw new BusinessException("更新文书送达截止日期时未指定文书目录编码");
        }
        CaseStageLinkRelateDocumentQueryDto queryDto = new CaseStageLinkRelateDocumentQueryDto();
        queryDto.setCaseId(caseId);
        queryDto.setCaseStageCode(documentCatalogCode);
        List<CaseStageLinkRelateDocumentVo> caseStageLinkRelateDocumentList
                = getCaseStageLinkRelateDocumentInfo(queryDto);
        if (ObjectUtils.isEmpty(caseStageLinkRelateDocumentList) || caseStageLinkRelateDocumentList.size() == 0) {
            throw new BusinessException("更新文书送达截止日期时未匹配到文书记录");
        } else if (caseStageLinkRelateDocumentList.size() > 1) {
            throw new BusinessException("案件：" + caseId + ",文书目录：" + documentCatalogCode + "存在冗余文书记录");
        } else if (caseStageLinkRelateDocumentList.size() == 1) {
            //计算文书送达截止日期
            //开始计算时间
            LocalDateTime now = LocalDateTime.now();
            ConfigBusiParamDocumentInfo configBusiParamDocumentInfo
                    = configBusiParamDocumentInfoService.getDetailByDocumentCatalogCode(documentCatalogCode);
            Integer day = configBusiParamDocumentInfo.getSendLimitDay();
            if (!ObjectUtils.isEmpty(day)) {
                String sendLimitType = configBusiParamDocumentInfo.getSendLimitType();
                LocalDate deadLine;
                if (LimitDayTypeEnum.NATURE_DAY.getCode().equals(sendLimitType)) {
                    deadLine = now.plusDays(day).toLocalDate();
                } else if (LimitDayTypeEnum.WORK_DAY.getCode().equals(sendLimitType)) {
                    String startDate = now.toLocalDate().toString();
                    ConfigEndDayQueryDto q = new ConfigEndDayQueryDto();
                    q.setStartDate(startDate);
                    q.setBeforeOrAfterSign(Constant.STRING_AFTER);
                    q.setType(Constant.STRING_0);
                    q.setDayCount(day);
                    q.setIsContainStartDay(YesOrNoEnum.NO.getCode());
                    deadLine = configWorkRestDayInfoService.getPeriodEndDate(q);
                } else {
                    throw new BusinessException("非法期限日期类型");
                }
                if (ObjectUtils.isEmpty(deadLine)) {
                    Example update = new Example(CaseDocumentRecord.class);
                    update.createCriteria().andEqualTo("caseId", caseId)
                            .andEqualTo("documentCatalogCode", documentCatalogCode)
                            //.andNotEqualTo("documentRecordStatus", DocumentRecordStatusEnum.WITHDRAW.getCode());
                            .andIn("documentRecordStatus", Arrays.asList(DocumentRecordStatusEnum.NORMAL.getCode(), DocumentRecordStatusEnum.DRAFT.getCode()));
                    //更新文书送达截止日期
                    CaseDocumentRecord caseDocumentRecord = new CaseDocumentRecord();
                    caseDocumentRecord.setSentDeadline(deadLine);
                    caseDocumentRecordMapper.updateByExampleSelective(caseDocumentRecord, update);
                } else {
                    throw new BusinessException("计算文书送达截止日期时出现异常");
                }
            } else {
                //无截止日期限制
                log.info("无截止日期限制 caseId:{} documentCatalogCode:{}", caseId, documentCatalogCode);
            }
        }
    }

    /**
     * 描述：计算送达截止日期
     *
     * @param caseId              案件id
     * @param documentCatalogCode 文书目录编码
     * @param sendLimitDay        送达期限
     * @param sendLimitType       送达期限类型
     * @param isContainStartDay   是否包含开始日期
     * @return LocalDate 送达截止日期
     * @author xiangyuyu
     * @date 2022-03-04 09:41
     */
    @Override
    public LocalDate calculateSentDeadLine(String caseId, String documentCatalogCode, Integer sendLimitDay, String sendLimitType, boolean isContainStartDay) {
        LocalDate deadLine = null;
        //计算文书送达截止日期
        //开始计算时间
        LocalDateTime now = LocalDateTime.now();
        Integer day = sendLimitDay;
        if (!ObjectUtils.isEmpty(day)) {
            if (LimitDayTypeEnum.NATURE_DAY.getCode().equals(sendLimitType)) {
                deadLine = now.plusDays(day).toLocalDate();
            } else if (LimitDayTypeEnum.WORK_DAY.getCode().equals(sendLimitType)) {
                String startDate = now.toLocalDate().toString();
                ConfigEndDayQueryDto q = new ConfigEndDayQueryDto();
                q.setStartDate(startDate);
                q.setBeforeOrAfterSign(Constant.STRING_AFTER);
                q.setType(Constant.STRING_0);
                q.setDayCount(day);
                q.setIsContainStartDay(YesOrNoEnum.NO.getCode());
                deadLine = configWorkRestDayInfoService.getPeriodEndDate(q);
            } else {
                throw new BusinessException("非法送达期限类型(1-工作日/2-自然日)");
            }
        } else {
            //无截止日期限制
            log.info("无截止日期限制 caseId:{} documentCatalogCode:{}", caseId, documentCatalogCode);
        }
        return deadLine;
    }

    /**
     * 描述：更新文书送达信息
     *
     * @param documentId 文书id
     * @param sentTime   送达时间
     * @param sendStatus 送达状态
     * @author xiangyuyu
     * @date 2022-03-04 09:41
     */
    @Override
    public void updateDocumentSentInfo(String documentId, LocalDateTime sentTime, String sendStatus) {
        //更新文书送达截止日期
        if (ObjectUtils.isEmpty(documentId)) {
            throw new BusinessException("updateDocumentSentInfo-未指定文书id");
        }
        if (ObjectUtils.isEmpty(sendStatus)) {
            throw new BusinessException("updateDocumentSentInfo-未指定发送状态");
        }
        //先查询
        CaseDocumentRecordVo documentRecordVo = getCaseDocumentRecordInfo(documentId);
        String a = documentRecordVo.getRealPlaceSentStatus();

        CaseDocumentRecord caseDocumentRecord = new CaseDocumentRecord();
        caseDocumentRecord.setSentTime(sentTime);
        String documentStatus = DocumentStatusEnum.WAIT_TO_SEND.getCode();
        if (DocumentSendStatusEnum.SEND_SUCCESS.getCode().equals(sendStatus)) {
            documentStatus = DocumentStatusEnum.SENT.getCode();
        }
        caseDocumentRecord.setDocumentSentStatus(documentStatus);
        Example updateExample = new Example(CaseDocumentRecord.class);
        updateExample.createCriteria().andEqualTo("id", documentId)
                //.andNotEqualTo("documentRecordStatus", DocumentRecordStatusEnum.WITHDRAW.getCode());
                .andIn("documentRecordStatus", Arrays.asList(DocumentRecordStatusEnum.NORMAL.getCode(), DocumentRecordStatusEnum.DRAFT.getCode()));
        caseDocumentRecordMapper.updateByExampleSelective(caseDocumentRecord, updateExample);
    }

    @Override
    public CaseDocumentRecordDetailVo getCaseDocumentRecordDetail(CaseDocumentRecordQueryDto infoQueryDto) {
        //多当事人合并处罚时将partyId置空
        CaseMainInfoVo vo = caseMainInfoService.getCaseMainInfo(infoQueryDto.getCaseId());
        String handleType = vo.getHandleType();
        String partiesReasonType = vo.getCasePartiesReasonType();
        if (PartiesReasonTypeEnum.MULTIPLE_PARTIES.getCode().equals(partiesReasonType) && HandleTypeEnum.MERGE_PUNISH.getCode().equals(handleType)) {
            infoQueryDto.setPartyId("");
        }
        return caseDocumentRecordMapper.selectCaseDocumentRecordDetail(infoQueryDto);
    }

    @Override
    public CaseDocumentRecordDetailVo getPunishInformInfo(CaseDocumentRecordQueryDto infoQueryDto) {
        CaseMainDetailInfo caseMainDetailInfo = caseMainDetailInfoService.getCaseMainDetailByCaseId(infoQueryDto.getCaseId());
        CaseMainInfoVo caseMainInfo = caseMainInfoService.getCaseMainInfo(infoQueryDto.getCaseId());

        String isHearing = caseMainDetailInfo.getIsHearing();
        CaseDocumentRecordQueryDto queryDto = new CaseDocumentRecordQueryDto();
        //单案由多当事人处理
        if (PartiesReasonTypeEnum.MULTIPLE_PARTIES.getCode().equals(caseMainInfo.getCasePartiesReasonType())
                && HandleTypeEnum.PART_PUNISH.getCode().equals(caseMainInfo.getHandleType())) {
            CaseMainDetailAuxiliaryInfoRequest request = new CaseMainDetailAuxiliaryInfoRequest(infoQueryDto.getCaseId(), infoQueryDto.getPartyId());
            List<CaseMainDetailAuxiliaryInfo> auxiliaryInfos = caseMainDetailAuxiliaryInfoService.getCaseMainDetailAuxiliaryInfo(request);
            CaseMainDetailAuxiliaryInfo auxiliaryInfo = new CaseMainDetailAuxiliaryInfo();
            if (ObjectUtil.isNotEmpty(auxiliaryInfo) && auxiliaryInfos.size() > 0) {
                isHearing = auxiliaryInfos.get(0).getIsHearing();
            }
            queryDto.setPartyId(infoQueryDto.getPartyId());
        }
        //处理告知书听证code
        String documentKindCode = "";
        if (Constant.STRING_1.equals(isHearing)) {
            documentKindCode = DocumentKindEnum.DOC_KIND_CFGZSTZL.getCode();
        } else {
            documentKindCode = DocumentKindEnum.DOC_KIND_CFGZS.getCode();
        }
        queryDto.setDocumentKindCode(documentKindCode);
        //列表为空
        if (ObjectUtil.isNotEmpty(infoQueryDto.getDocumentKindCodeList())) {
            queryDto.setDocumentKindCode("");
            queryDto.setDocumentKindCodeList(infoQueryDto.getDocumentKindCodeList());
        }
        queryDto.setCaseId(infoQueryDto.getCaseId());

        return caseDocumentRecordMapper.selectCaseDocumentRecordDetail(queryDto);
    }

    @Override
    public CaseDocumentRecord getCaseDocumentRecord(String caseId, String documentCatalogCode) {
        //查询文书记录数据
        Example example = new Example(CaseDocumentRecord.class);
        example.createCriteria().andEqualTo("caseId", caseId).andEqualTo("documentCatalogCode", documentCatalogCode)
                //.andNotEqualTo("documentRecordStatus", DocumentRecordStatusEnum.WITHDRAW.getCode());
                .andIn("documentRecordStatus", Arrays.asList(DocumentRecordStatusEnum.NORMAL.getCode(), DocumentRecordStatusEnum.DRAFT.getCode()));
        List<CaseDocumentRecord> caseDocumentRecordList = caseDocumentRecordMapper.selectByExample(example);
        if (caseDocumentRecordList == null || caseDocumentRecordList.size() == 0) {
            return null;
        }
        return caseDocumentRecordList.get(0);
    }

    /**
     * 获取文书记录--通用方法
     *
     * @return {@link CaseDocumentRecord}
     * @author: zhengqiang
     * @date: 2022/5/18
     * @param: caseId
     * @param: documentCatalogCode
     * @param: partyId
     **/
    @Override
    public CaseDocumentRecord getCaseDocumentRecord(String caseId, String documentCatalogCode, String partyId) {
        //查询文书记录数据
        Example example = new Example(CaseDocumentRecord.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("caseId", caseId).andEqualTo("documentCatalogCode", documentCatalogCode)
                //.andNotEqualTo("documentRecordStatus", DocumentRecordStatusEnum.WITHDRAW.getCode());
                .andIn("documentRecordStatus", Arrays.asList(DocumentRecordStatusEnum.NORMAL.getCode(), DocumentRecordStatusEnum.DRAFT.getCode()));
        example.orderBy("documentCreateTime").desc();
        if (!ObjectUtils.isEmpty(partyId)) {
            //根据目录编码查询
            ConfigBusiParamDocumentInfo configBusiParamDocumentInfo = configBusiParamDocumentInfoService.getDetailByDocumentCatalogCode(documentCatalogCode);
            String documentKindCode = configBusiParamDocumentInfo.getDocumentKindCode();
            //文书关联对象是2:当事人
            if (DocumentLinkObjectTypeEnum.PERSON.getCode().equals(configBusiParamDocumentInfo.getDocumentLinkObjectType())) {
                //判断是否为多当事人合并处罚
                CaseMainInfoVo caseMainInfo = caseMainInfoService.getCaseMainInfo(caseId);
                String handleType = caseMainInfo.getHandleType();
                String partiesReasonType = caseMainInfo.getCasePartiesReasonType();
                // FIXME: 2022/8/2 sentRelatedNeedPartyIdKindCodeList
                if (!HandleTypeEnum.MERGE_PUNISH.getCode().equals(handleType)
                        || sentRelatedNeedPartyIdDocumentKindCodeList.contains(documentKindCode)) {
                    criteria.andEqualTo("partyId", partyId);
                }
            }
        }
        List<CaseDocumentRecord> caseDocumentRecordList = caseDocumentRecordMapper.selectByExample(example);
        if (caseDocumentRecordList == null || caseDocumentRecordList.size() == 0) {
            return null;
        }
        return caseDocumentRecordList.get(0);
    }

    /**
     * 描述：获取案件有效文书列表
     *
     * @param caseId 案件id, caseAssistId 案件副流程id
     * @return {@link List<CaseDocumentRecord> }
     * @author shishengyao
     * @date 2022/04/07
     */
    @Override
    public List<CaseDocumentRecordDto> getCaseDocumentRecordList(String caseId, String caseAssistId) {
        return caseDocumentRecordMapper.selectCaseDocumentRecordDto(caseId, caseAssistId);
    }

    @Override
    public CaseDocumentRecordDto getCaseDocumentRecordByKindCode(String caseId, String documentKindCode) {
        return caseDocumentRecordMapper.selectCaseDocumentRecordByKindCode(caseId, documentKindCode);
    }

    @Override
    public CaseDocumentRecordDto selectCaseDocumentRecordByKindCodeAndPartyId(String caseId, String documentKindCode, String partyId) {
        return caseDocumentRecordMapper.selectCaseDocumentRecordByKindCodeAndPartyId(caseId, documentKindCode, partyId);
    }

    /**
     * 描述：获取指定文书种类的文书记录
     *
     * @param documentKindCode 文书目录编码
     * @param sentDate         指定送达日期
     * @param createDate       文书创建日期
     * @return {@link List<CaseDocumentRecordVo>} 文书记录
     * @author xiangyuyu
     * @date 2022-04-14 11:04
     */
    @Override
    public List<CaseDocumentRecordVo> getCaseDocumentRecordListWithKindCode(String documentKindCode, String sentDate, String createDate) {
        return caseDocumentRecordMapper.selectCaseDocumentRecordListWithKindCode(documentKindCode, sentDate, createDate);
    }

    /**
     * 描述：根据指定条件查询文书记录信息
     *
     * @param queryDto {@link CaseDocumentRecordQueryDto}
     * @return List<CaseDocumentRecordVo> 文书记录信息
     * @author xiangyuyu
     * @date 2022-07-01 14:28
     */
    @Override
    public List<CaseDocumentRecordVo> getCaseDocumentRecordList(CaseDocumentRecordQueryDto queryDto) {
        List<CaseDocumentRecordVo> list = caseDocumentRecordMapper.selectCaseDocumentRecordList(queryDto);
        return list;
    }

    @Override
    public List<CaseDocumentRecordVo> getCaseDocumentCxRecordList(CaseDocumentRecordQueryDto queryDto) {
        List<CaseDocumentRecordVo> list = caseDocumentRecordMapper.selectCaseDocumentRecordCxjdfList(queryDto);
        return list;
    }

    /**
     * 【V1.1.0】描述：获取案件id列表-需要上报的调查信息
     *
     * @return {@link List<String>} 案件id列表
     * @author xiangyuyu
     * @date 2022-02-16 16:02
     */
    @Override
    public List<String> getCaseIdListShouldReportInvestigateInfo() {
        if (Constant.STRING_DATA_REPORT_STAGE_SWITCH_OPEN.equals(dataReportStageSwitch)) {
            return caseDocumentRecordMapper.selectCaseIdListShouldReportInvestigateInfo();
        }
        return caseDocumentRecordMapper.selectCaseIdListShouldReportInvestigateInfoRefactor();
    }

    /**
     * 【V1.1.0】描述：获取案件id列表-需要上报的调查信息
     *
     * @return {@link List<String>} 案件id列表
     * @author mahan
     * @date 2022-10-20 16:02
     */
    @Override
    public List<String> getCaseIdListShouldReportInvestigateInfo(List<String> punishDecideCaseIdList) {
        return caseDocumentRecordMapper.selectReportInvestigateInfoCaseIdList(punishDecideCaseIdList);
    }

    /**
     * 【V1.1.0】描述：获取案件id列表-需要上报的告知信息
     *
     * @return {@link List<String>} 案件id列表
     * @author xiangyuyu
     * @date 2022-02-16 16:02
     */
    @Override
    public List<String> getCaseIdListShouldReportInformInfo() {
        if (Constant.STRING_DATA_REPORT_STAGE_SWITCH_OPEN.equals(dataReportStageSwitch)) {
            return caseDocumentRecordMapper.selectCaseIdListShouldReportInformInfo();
        }
        return caseDocumentRecordMapper.selectCaseIdListShouldReportInformInfoRefactor();
    }

    /**
     * 【V1.1.0】描述：获取案件id列表-需要上报的告知信息
     *
     * @return {@link List<String>} 案件id列表
     * @author mahan
     * @date 2022-10-20 16:02
     */
    @Override
    public List<String> getCaseIdListShouldReportInformInfo(List<String> punishDecideCaseIdList) {
        return caseDocumentRecordMapper.selectReportInformInfoCaseIdList(punishDecideCaseIdList);
    }


    /**
     * 【V2.0.0】描述：获取案件id列表-需要上报的听证类告知信息
     *
     * @return {@link List<String>} 案件id列表
     * @author xiangyuyu
     * @date 2022-06-15 10:30
     */
    @Override
    public List<String> getCaseIdListShouldReportHearingInformInfo() {
        if (Constant.STRING_DATA_REPORT_STAGE_SWITCH_OPEN.equals(dataReportStageSwitch)) {
            return caseDocumentRecordMapper.selectCaseIdListShouldReportHearingInformInfo();
        }
        return caseDocumentRecordMapper.selectCaseIdListShouldReportHearingInformInfoRefactor();
    }

    /**
     * 【V2.0.0】描述：获取案件id列表-需要上报的听证类告知信息
     *
     * @return {@link List<String>} 案件id列表
     * @author mahan
     * @date 2022-10-20 19:30
     */
    @Override
    public List<String> getCaseIdListShouldReportHearingInformInfo(List<String> punishDecideCaseIdList) {
        return caseDocumentRecordMapper.selectReportHearingInformCaseIdList(punishDecideCaseIdList);
    }

    /**
     * 【V1.1.0】描述：获取案件id列表-需要上报的决定信息
     *
     * @return {@link List<String>} 案件id列表
     * @author xiangyuyu
     * @date 2022-02-16 16:02
     */
    @Override
    public List<String> getCaseIdListShouldReportDecideInfo() {
        if (Constant.STRING_DATA_REPORT_STAGE_SWITCH_OPEN.equals(dataReportStageSwitch)) {
            List<String> shouldReportDecideInfoCaseIdList = caseDocumentRecordMapper.selectCaseIdListShouldReportDecideInfo();
            //决定数据上报优化(处罚办案系统2.0中，作出处罚决定书后，但未在10个工作日内送达处罚决定书，系统将在第11个工作日推送公示信息至省大数据局)
            List<String> caseIdListDecideInfoAfterTenDays = getCaseIdListDecideInfoAfterTenWorkDays();
            shouldReportDecideInfoCaseIdList.addAll(caseIdListDecideInfoAfterTenDays);
            return shouldReportDecideInfoCaseIdList;
        }
        return caseDocumentRecordMapper.selectCaseIdListShouldReportDecideInfoRefactor();
    }

    /**
     * 【V1.11.7】描述： 获取作出处罚决定书后，超过10个工作日未送达的决定信息
     *
     * @return {@link List< String>}
     * @author: zhengqiang
     * @date: 2023/5/24
     **/
    public List<String> getCaseIdListDecideInfoAfterTenWorkDays() {
        Set<String> set = new HashSet<>();
        //先获取超过10日未送达的决定案件列表
        List<CaseDecideInfoVo> caseDecideInfoVos = caseDocumentRecordMapper.selectCaseDecideInfoListAfterTenDays();
        //筛选出超过10个工作日未送达的决定案件列表
        caseDecideInfoVos.forEach(e -> {
            String startDate = e.getDocumentApprovalTime().toLocalDate().toString();
            ConfigEndDayQueryDto q = new ConfigEndDayQueryDto();
            q.setStartDate(startDate);
            q.setBeforeOrAfterSign(Constant.STRING_AFTER);
            q.setType(Constant.STRING_0);
            q.setDayCount(10);
            q.setIsContainStartDay(YesOrNoEnum.NO.getCode());
            LocalDate periodEndDate = configWorkRestDayInfoService.getPeriodEndDate(q);
            if (LocalDate.now().isAfter(periodEndDate)) {
                set.add(e.getCaseId());
            }
        });
        return set.stream().collect(Collectors.toList());
    }

    /**
     * 【V2.0.0】描述：根据特定信息查询文书关键信息【所有文书通用】
     *
     * @param request {@link DocumentKeyInfoRequest}
     * @return {@link CaseDocumentKeyInfoVo} 文书关键信息
     * @author xiangyuyu
     * @date 2022-02-16 16:02
     */
    @Override
    public CaseDocumentKeyInfoVo getDocumentKeyInfoBySpecialCondition(DocumentKeyInfoRequest request) {

        CaseDocumentKeyInfoVo vo;
        String id = request.getId();
        String documentCatalogCode = request.getDocumentCatalogCode();
        String caseId = request.getCaseId();
        String partyId = request.getPartyId();
        CaseDocumentRecord record = new CaseDocumentRecord();
        if (ObjectUtils.isEmpty(id)) {
            if (ObjectUtils.isEmpty(documentCatalogCode) || ObjectUtils.isEmpty(caseId)) {
                throw new BusinessException("未指定主键id时请指定文书目录编码和案件id");
            }
            CaseMainInfoVo caseMainInfo = caseMainInfoService.getCaseMainInfo(caseId);
            String isShowPartiesSelector = caseMainInfoService.validateIsShowPartiesSelector(caseMainInfo, null);
            if (YesOrNoEnum.YES.getCode().equals(isShowPartiesSelector)
                    && ObjectUtils.isEmpty(partyId)) {
                throw new BusinessException("多当事人分别处罚时请指定当事人id");
            }
            Example query = new Example(CaseDocumentRecord.class);
            Example.Criteria criteria = query.createCriteria();
            if (!ObjectUtils.isEmpty(partyId)) {
                criteria.andEqualTo("partyId", partyId);
            }
            if (!ObjectUtils.isEmpty(partyId)) {
                criteria.andEqualTo("caseId", caseId);
            }
            if (!ObjectUtils.isEmpty(partyId)) {
                criteria.andEqualTo("documentCatalogCode", documentCatalogCode);
            }
            //criteria.andNotEqualTo("documentRecordStatus", DocumentRecordStatusEnum.WITHDRAW.getCode());
            criteria.andIn("documentRecordStatus", Arrays.asList(DocumentRecordStatusEnum.NORMAL.getCode(), DocumentRecordStatusEnum.DRAFT.getCode()));
            List<CaseDocumentRecord> list = caseDocumentRecordMapper.selectByExample(query);
            if (!ObjectUtils.isEmpty(list) && list.size() > 0) {
                record = list.get(Constant.INTEGER_0);
            }
        } else {
            record = caseDocumentRecordMapper.selectByPrimaryKey(id);

        }
        if (ObjectUtils.isEmpty(record)) {
            throw new BusinessException("未匹配到文书记录 request:" + request);
        }
        vo = new CaseDocumentKeyInfoVo();
        BeanUtils.copyProperties(record, vo);
        return vo;
    }

    /**
     * 查询未执行的处罚决定书列表
     *
     * @return {@link List< CaseDocumentRecordVo>}
     * @author: zhengqiang
     * @date: 2022/5/31
     * @param: documentOfUnExecuteQueryDto
     **/
    @Override
    public List<CaseDocumentRecordVo> getDocumentRecordOfUnExecute(DocumentOfUnExecuteQueryDto documentOfUnExecuteQueryDto) {
        //查询业务参数配置id
        CaseMainInfoVo caseMainInfo = caseMainInfoService.getCaseMainInfo(documentOfUnExecuteQueryDto.getCaseId());
        String busiParamId = caseMainInfo.getBusiParamId();
        ConfigBusiParamDocumentInfo configBusiParamDocumentInfo = configBusiParamDocumentInfoService.getDocumentInfoByDocumentKindCode(busiParamId, documentOfUnExecuteQueryDto.getDocumentKindCode());

        List<CaseDocumentRecordVo> caseDocumentRecordVos = new ArrayList<>();
        Example exampleDocRed = new Example(CaseDocumentRecord.class);
        Example.Criteria criteria = exampleDocRed.createCriteria();
        criteria.andEqualTo("caseId", documentOfUnExecuteQueryDto.getCaseId()).andEqualTo("documentCatalogCode", configBusiParamDocumentInfo.getDocumentCatalogCode())
                //.andNotEqualTo("documentRecordStatus", DocumentRecordStatusEnum.WITHDRAW.getCode());
                .andIn("documentRecordStatus", Arrays.asList(DocumentRecordStatusEnum.NORMAL.getCode(), DocumentRecordStatusEnum.DRAFT.getCode()));
        if (!ObjectUtils.isEmpty(documentOfUnExecuteQueryDto.getPartyId())) {
            criteria.andEqualTo("partyId", documentOfUnExecuteQueryDto.getPartyId());
        }
        List<CaseDocumentRecord> caseDocumentRecords = caseDocumentRecordMapper.selectByExample(exampleDocRed);

        caseDocumentRecords.forEach(e -> {
            //排除已执行过的处罚决定书记录
            int count = caseDocumentRecordMapper.getExecuteDocumentRecordCount(e.getCaseId(), e.getPartyId());
            if (count > 0) {
                return;
            }
            CaseDocumentRecordVo vo = new CaseDocumentRecordVo();
            BeanUtils.copyProperties(e, vo);
            caseDocumentRecordVos.add(vo);
        });

        return caseDocumentRecordVos;
    }

    @Override
    public List<CaseDocumentRecordDetailVo> getCaseDocumentRecordDocNumberInfoList(CaseDocumentRecordCommonQueryDto queryDto) {
        //如果是处罚决定书，则特殊处理，查询处罚决定书和不予处罚决定书
        if (Constant.STRING_1.equals(queryDto.getIsPunishDocument())) {
            queryDto.setDocumentKindCode("");
        }
        CaseMainInfoVo caseMainInfo = caseMainInfoService.getCaseMainInfo(queryDto.getCaseId());
        if (PartiesReasonTypeEnum.MULTIPLE_PARTIES.getCode().equals(caseMainInfo.getCasePartiesReasonType()) && HandleTypeEnum.PART_PUNISH.getCode().equals(caseMainInfo.getHandleType())) {
            queryDto.setPartyId(queryDto.getPartyId());
        } else {
            queryDto.setPartyId("");
        }
        return caseDocumentRecordMapper.selectCaseDocumentRecordDocNumberInfoList(queryDto);
    }

    @Override
    public CaseDocumentSingleRecordVo getCaseDocumentRecordForCommon(CaseDocumentRecordQueryDto queryDto) {

        //多当事人合并处罚时将partyId置空
        CaseMainInfoVo vo = caseMainInfoService.getCaseMainInfo(queryDto.getCaseId());
        String handleType = vo.getHandleType();
        String partiesReasonType = vo.getCasePartiesReasonType();

        String investConclusion = "";
        String isHearing = "";

        //处理关联送达文书
        dealMatchSendDocumentCatalogCode(queryDto);

        if (PartiesReasonTypeEnum.MULTIPLE_PARTIES.getCode().equals(partiesReasonType)
                && HandleTypeEnum.PART_PUNISH.getCode().equals(vo.getHandleType())) {
            CaseMainDetailAuxiliaryInfoRequest request = new CaseMainDetailAuxiliaryInfoRequest();
            request.setCaseId(queryDto.getCaseId());
            request.setPartyId(queryDto.getPartyId());
            List<CaseMainDetailAuxiliaryInfo> auxiliaryInfos = caseMainDetailAuxiliaryInfoService.getCaseMainDetailAuxiliaryInfo(request);
            CaseMainDetailAuxiliaryInfo auxiliaryInfo = new CaseMainDetailAuxiliaryInfo();
            if (ObjectUtil.isNotEmpty(auxiliaryInfo) && auxiliaryInfos.size() > 0) {
                auxiliaryInfo = auxiliaryInfos.get(0);
            }
            queryDto.setPartyId(queryDto.getPartyId());
            investConclusion = auxiliaryInfo.getInvestConclusion();
            isHearing = auxiliaryInfo.getIsHearing();
        } else {
            CaseMainDetailInfo caseMainDetailInfo = caseMainDetailInfoService.getCaseMainDetailByCaseId(queryDto.getCaseId());
            investConclusion = caseMainDetailInfo.getInvestConclusion();
            isHearing = caseMainDetailInfo.getIsHearing();
            queryDto.setPartyId("");
        }

        //若为处罚决定 判断是否为不予处罚
        if (DocumentKindEnum.DOC_KIND_CFJDS.getCode().equals(queryDto.getDocumentKindCode())) {
            //不予处罚
            if (Constant.STRING_2.equals(investConclusion)) {
                queryDto.setDocumentKindCode(DocumentKindEnum.DOC_KIND_BYCFJDS.getCode());
            } else {
                //予以处罚
                queryDto.setDocumentKindCode(DocumentKindEnum.DOC_KIND_CFJDS.getCode());
            }
            queryDto.setRelateDocumentCatalogCode("");
        }
        if (DocumentKindEnum.DOC_KIND_CFGZS.getCode().equals(queryDto.getDocumentKindCode())) {
            //非听证类
            if (Constant.STRING_1.equals(isHearing)) {
                queryDto.setDocumentKindCode(DocumentKindEnum.DOC_KIND_CFGZSTZL.getCode());
            } else {
                //听证类
                queryDto.setDocumentKindCode(DocumentKindEnum.DOC_KIND_CFGZS.getCode());
            }
            queryDto.setRelateDocumentCatalogCode("");
        }
        CaseDocumentSingleRecordVo recordVo = new CaseDocumentSingleRecordVo();
        CaseDocumentRecordDetailVo caseDocumentRecordDetailVo = caseDocumentRecordMapper.selectCaseDocumentRecordDetail(queryDto);
        BeanUtils.copyProperties(caseDocumentRecordDetailVo, recordVo);
        //如果是补正/更正，则根据BeServedDocumentId查询，并覆盖结果
        if (StrUtil.isNotEmpty(queryDto.getBeServedDocumentId())) {
            CaseDocumentRecord caseDocumentRecord = caseDocumentRecordMapper.selectByPrimaryKey(queryDto.getBeServedDocumentId());
            if (caseDocumentRecord != null) {
                ConfigBusiParamDocumentInfo configBusiParamDocumentInfo = configBusiParamDocumentInfoService.getDetailByDocumentCatalogCode(caseDocumentRecord.getDocumentCatalogCode());
                String documentKindCode = configBusiParamDocumentInfo.getDocumentKindCode();
                if (DocumentKindEnum.DOC_KIND_DK2BZGZTZS.getCode().equals(documentKindCode)) {
                    BeanUtils.copyProperties(caseDocumentRecord, recordVo);
                    recordVo.setDocumentId(caseDocumentRecord.getId());
                }
            }
        }
        recordVo.setDemandHearingOpinion("");
        recordVo.setDemandStatementPleadOpinion("");
        recordVo.setFulfillInformAndpartyOpinion("");
        recordVo.setIsHearing(isHearing);
        return recordVo;
    }

    /**
     * 处理关联送达文书信息
     *
     * @param queryDto
     */
    private void dealMatchSendDocumentCatalogCode(CaseDocumentRecordQueryDto queryDto) {
        if (!Constant.STRING_1.equals(queryDto.getIsMatchSentDocument()) || StrUtil.isEmpty(queryDto.getDocumentCatalogCode())) {
            //清空该字段查询，该字段之前没有筛选
            queryDto.setDocumentCatalogCode(null);
            return;
        }
        ConfigBusiParamDocumentInfo config = configBusiParamDocumentInfoService.getDetailByDocumentCatalogCode(queryDto.getDocumentCatalogCode());
        if (StrUtil.isNotEmpty(config.getMatchSentDocumentCatalogCode())) {
            queryDto.setDocumentCatalogCode(config.getMatchSentDocumentCatalogCode());
        } else {
            //清空该字段查询，该字段之前没有筛选
            queryDto.setDocumentCatalogCode(null);
        }
    }

    /**
     * 【V1.3.0】描述：根据环节编码撤回文书记录
     *
     * @return
     * @author tianrunjia
     * @date 2022-06-27
     */
    @Override
    public void recallCaseDocumentRecordByCaseLinkCode(String caseId, String caseLinkCode) {
        //排除关联类文书
        List<ConfigWorkFlowDocument> configWorkFlowDocumentList = configWorkFlowDocumentService.getConfigWorkFlowDocumentRelatedListByFlowCode("", "", caseLinkCode);
        List<String> relatedDocument = new ArrayList<>();
        if (configWorkFlowDocumentList.size() > 0) {
            configWorkFlowDocumentList.forEach(f -> {
                relatedDocument.add(f.getDocumentCatalogCode());
            });
        } else {
            relatedDocument.add("111");
        }
        //排除案件操作文书
        CaseMainInfoVo caseMainInfo = caseMainInfoService.getCaseMainInfo(caseId);
        List<ConfigWorkFlowOperateDetailInfo> configWorkFlowOperateDetailInfoList = configWorkFlowOperateDetailInfoService.getConfigWorkFlowOperateDetailInfoListByLinkCode(caseMainInfo.getCaseFlowCode(), caseLinkCode);
        if (configWorkFlowOperateDetailInfoList.size() > 0) {
            configWorkFlowOperateDetailInfoList.forEach(f -> {
                // todo 待优化 目前特定处理调整当事人文书
                //操作类型 1-下一环节 2-更多操作 3-其它文书   操作对象类型 1-对案件 2-对当事人 3-混合
                //调整当事人的文书不撤回 案件类型的文书不撤回
                if (ObjectUtil.isNotEmpty(f.getDocumentCatalogCode())
                        && ObjectUtil.isNotEmpty(f.getFrontSymble())
                        && "001_1".equals(f.getFrontSymble())) {
                    relatedDocument.add(f.getDocumentCatalogCode());
                }
            });
        }

        List<CaseDocumentRecord> caseDocumentRecordList = caseDocumentRecordMapper.selectCaseDocumentRecordListWithSentRecord(caseId, caseLinkCode, "3");
        if (caseDocumentRecordList.size() > 0) {
            caseDocumentRecordList.forEach(e -> {
                documentSendRecordService.doRemoveDocumentSendRecord(e.getId(), e.getCaseId());
            });
        }

        //撤回修改文书待审批记录
        Example example = new Example(CaseDocumentRecord.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("caseId", caseId).andEqualTo("caseLinkCode", caseLinkCode)
                .andNotEqualTo("documentRecordStatus", DocumentRecordStatusEnum.WITHDRAW.getCode());
        List<CaseDocumentRecord> documentRecords = caseDocumentRecordMapper.selectByExample(example);
        if (ObjectUtil.isNotEmpty(documentRecords)) {
            documentRecords.forEach(e -> {
                //查询是否存在修改文书审批记录
                if (YesOrNoEnum.YES.getCode().equals(e.getIsModifyRecord())) {
                    Example queryExample = new Example(CaseApprovalWaitRecord.class);
                    queryExample.createCriteria().andEqualTo("caseId", caseId).andEqualTo("docId", e.getId());
                    List<CaseApprovalWaitRecord> waitRecordList = caseApprovalWaitRecordMapper.selectByExample(queryExample);
                    if (ObjectUtil.isNotEmpty(waitRecordList)) {
                        CaseApprovalWaitRecord waitRecord = waitRecordList.get(0);
                        caseApprovalWaitRecordService.dealApprovalWaitRecord(waitRecord);

                    }

                }
            });
        }


        //作废文书修改记录
        caseDocumentModifyRecordMapper.updateRecallCaseDocumentModifyRecordByCaseLinkCode(caseId, caseLinkCode, relatedDocument);


        caseDocumentRecordMapper.updateRecallCaseDocumentRecordByCaseLinkCode(caseId, caseLinkCode, relatedDocument);
        // 案件状态变更记录撤回
        caseMainInfoStatusChangeRecordService.recallCaseMainInfoStatusChangeRecordByCaseLinkCode(caseId, caseLinkCode);
    }

    /**
     * 描述：获取app文书记录
     *
     * @param dto {@link AppCaseDocumentRecordDto}doRecallCaseHandleLink
     * @return List<AppCaseBeforeDocumentRecordVo> app文书记录
     * @author xiangyuyu
     * @date 2022-06-30 20:43
     */
    @Override
    public List<AppCaseBeforeDocumentRecordVo> getAppCaseBeforeDocumentRecordList(AppCaseDocumentRecordDto dto) {
        List<AppCaseBeforeDocumentRecordVo> list = caseDocumentRecordMapper.selectAppCaseBeforeDocumentRecordList(dto);
        return list;
    }

    /**
     * 签字捺印版未签字原文件发送-案源
     *
     * @param signQueryDto
     * @return {@link SignSendFileVo}
     * @author liyafeng
     * @date 2022/8/18
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public SignSendFileVo getUnSignDoc(SignCaseSourceQueryDto signQueryDto) {
        SignSendFileVo vo = new SignSendFileVo();
        String documentCatalogCode = signQueryDto.getDocCategoryCode();
        String caseSourceId = signQueryDto.getCaseSourceId();

        String partyId = signQueryDto.getPartyId();
        CaseSourceDocumentRecord caseSourceDocumentRecord = caseSourceDocumentRecordService.getCaseDocumentRecord(caseSourceId, documentCatalogCode, partyId);
        vo.setCaseId(signQueryDto.getCaseSourceId());
        vo.setDocCategoryCode(signQueryDto.getDocCategoryCode());
        vo.setPartyId(signQueryDto.getPartyId());
        if (caseSourceDocumentRecord != null) {
            // 重新生成带签字确认日期的原文件
            CSourceDocCommonOperateSaveDto saveDto = new CSourceDocCommonOperateSaveDto();
            saveDto.setCaseSourceId(signQueryDto.getCaseSourceId());
            saveDto.setDocumentCatalogCode(signQueryDto.getDocCategoryCode());
            saveDto.setPartyId(signQueryDto.getPartyId());
            JSONObject jsonObject = JSON.parseObject(caseSourceDocumentRecord.getDocumentContent());
            HashMap<String, Object> jsonMap = new HashMap<>(16);
            for (Map.Entry<String, Object> entry : jsonObject.entrySet()) {
                jsonMap.put(entry.getKey(), entry.getValue());
            }
            jsonMap.put("signTime", LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy年M月d日")));
            saveDto.setDataMap(jsonMap);
            saveDto.setIsUpdateRelationTable(Constant.STRING_0);
            // 重新生成文书
            Map<String, Object> resultMap = cSourceDocCommonOperateService.saveDocInfo(saveDto);
            String st = "true";
            String success = "success";
            if (!st.equals(resultMap.get(success).toString())) {
                throw new BusinessException("获取文书失败！");
            }
            // 生成后重新查询
            caseSourceDocumentRecord = caseSourceDocumentRecordService.getCaseDocumentRecord(caseSourceId, documentCatalogCode, partyId);
            InputStream is = null;
            if (StringUtils.isNotBlank(caseSourceDocumentRecord.getDocumentUrlAfterSeal())) {
                is = HttpUtil.createGet(caseSourceDocumentRecord.getDocumentUrlAfterSeal()).execute().bodyStream();
            } else {
                is = HttpUtil.createGet(caseSourceDocumentRecord.getDocumentUrl()).execute().bodyStream();
            }
            // 文件转为base64
            vo.setDocStr(Base64.encode(is));
        } else {
            log.error("未匹配到文书记录-getUnSignDoc,caseId:{},partyId:{},documentCatalogCode:{}", caseSourceId, partyId, documentCatalogCode);
            throw new BusinessException("未匹配到文书记录-getUnSignDoc");
        }
        return vo;
    }

    /**
     * 签字捺印版未签字原文件发送-才走分离
     *
     * @param signQueryDto
     * @return {@link SignSendFileVo}
     * @author liyafeng
     * @date 2022/8/18
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public SignSendFileVo getExecuteUnSignDoc(SignExecuteQueryDto signQueryDto) {
        SignSendFileVo vo = new SignSendFileVo();
        String documentCatalogCode = signQueryDto.getDocCategoryCode();
        String executeId = signQueryDto.getCaseSourceId();

        String partyId = signQueryDto.getPartyId();
        ExecuteDocumentRecord executeSourceDocumentRecord = executeDocumentRecordService.getExecuteDocumentRecord(executeId, documentCatalogCode, partyId);
        vo.setCaseId(signQueryDto.getCaseSourceId());
        vo.setDocCategoryCode(signQueryDto.getDocCategoryCode());
        vo.setPartyId(signQueryDto.getPartyId());
        if (executeSourceDocumentRecord != null) {
            // 重新生成带签字确认日期的原文件
            ExecuteDocCommonOperateSaveDto saveDto = new ExecuteDocCommonOperateSaveDto();
            saveDto.setExecuteId(signQueryDto.getCaseSourceId());
            saveDto.setDocumentCatalogCode(signQueryDto.getDocCategoryCode());
            saveDto.setPartyId(signQueryDto.getPartyId());
            JSONObject jsonObject = JSON.parseObject(executeSourceDocumentRecord.getDocumentContent());
            HashMap<String, Object> jsonMap = new HashMap<>(16);
            for (Map.Entry<String, Object> entry : jsonObject.entrySet()) {
                jsonMap.put(entry.getKey(), entry.getValue());
            }
            jsonMap.put("signTime", LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy年MM月dd日")));
            saveDto.setDataMap(jsonMap);
            saveDto.setIsUpdateRelationTable(Constant.STRING_0);
            // 重新生成文书
            Map<String, Object> resultMap = executeDocCommonOperateService.saveDocInfo(saveDto);
            String st = "true";
            String success = "success";
            if (!st.equals(resultMap.get(success).toString())) {
                throw new BusinessException("获取文书失败！");
            }
            // 生成后重新查询
            executeSourceDocumentRecord = executeDocumentRecordService.getExecuteDocumentRecord(executeId, documentCatalogCode, partyId);
            InputStream is = null;
            if (StringUtils.isNotBlank(executeSourceDocumentRecord.getDocumentUrlAfterSeal())) {
                is = HttpUtil.createGet(executeSourceDocumentRecord.getDocumentUrlAfterSeal()).execute().bodyStream();
            } else {
                is = HttpUtil.createGet(executeSourceDocumentRecord.getDocumentUrl()).execute().bodyStream();
            }
            // 文件转为base64
            vo.setDocStr(Base64.encode(is));
        } else {
            log.error("未匹配到文书记录-getUnSignDoc,caseId:{},partyId:{},documentCatalogCode:{}", executeId, partyId, documentCatalogCode);
            throw new BusinessException("未匹配到文书记录-getUnSignDoc");
        }
        return vo;
    }

    /**
     * 接收捺印板回传已签字文书-案源
     *
     * @param signReceiveDto
     * @return {@link Map< String, Object>}
     * @author liyafeng
     * @date 2022/8/18
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int receiveSignDoc(SignCaseSourceReturnDto signReceiveDto) {
        log.info("receiveSignDoc start... signReceiveDto:{}", signReceiveDto);
        if (ObjectUtils.isEmpty(signReceiveDto)) {
            throw new BusinessException("未指定文书案件相关信息");
        }
        String caseSourceId = signReceiveDto.getCaseSourceId();
        if (ObjectUtils.isEmpty(caseSourceId)) {
            throw new BusinessException("未指定案源id");
        }
        String docCategoryCode = signReceiveDto.getDocCategoryCode();
        if (ObjectUtils.isEmpty(docCategoryCode)) {
            throw new BusinessException("未指定文书目录编码");
        }
        String partyId = signReceiveDto.getPartyId();
        String documentCatalogCode = signReceiveDto.getDocCategoryCode();
        CaseSourceDocumentRecord caseSourceDocumentRecordUpdate = caseSourceDocumentRecordService.getCaseDocumentRecord(caseSourceId, documentCatalogCode, partyId);

        if (caseSourceDocumentRecordUpdate == null) {
            log.error("未匹配到文书记录-receiveSignDoc,caseId:{},partyId:{},documentCatalogCode:{}", partyId, partyId, documentCatalogCode);
            throw new BusinessException("未匹配到文书记录-receiveSignDoc");
        }
        // 法度签字捺印保存requestId 到content 里
        String documentContent = caseSourceDocumentRecordUpdate.getDocumentContent();
        JSONObject documentContentJson = JSON.parseObject(documentContent);
        documentContentJson.put("requestId", signReceiveDto.getRequestId());
        documentContentJson.put("signDeviceType", signReceiveDto.getSignDeviceType());
        caseSourceDocumentRecordUpdate.setDocumentContent(documentContentJson.toJSONString());
        caseSourceDocumentRecordUpdate.setSignTime(new Date());

        // 保存法度签字捺印视频和文件
        if (Constant.STRING_2.equals(signReceiveDto.getSignDeviceType())) {
            try {
                FaduSignAttachmentFileSaveDto attachmentFileSaveDto = new FaduSignAttachmentFileSaveDto();
                attachmentFileSaveDto.setWorkId(signReceiveDto.getCaseSourceId());
                attachmentFileSaveDto.setBusinessType(Constant.STRING_2);
                attachmentFileSaveDto.setDocCategoryCode(signReceiveDto.getDocCategoryCode());
                attachmentFileSaveDto.setPartyId(partyId);
                faduSignService.saveSignZip(attachmentFileSaveDto, signReceiveDto.getRequestId());
            } catch (Exception e) {
                e.printStackTrace();
                log.info("法度签字捺印视频和文件失败，workId:{},docCategoryCode:{},requestId:{},", signReceiveDto.getCaseSourceId(), docCategoryCode, signReceiveDto.getRequestId());

            }
        }
        String signDocumentUrl = "";
        //海康的设备直接获取签字后地址
        if (Constant.STRING_1.equals(signReceiveDto.getSignDeviceType()) && ObjectUtil.isNotEmpty(signReceiveDto.getSignDocUrl())) {
            signDocumentUrl = signReceiveDto.getSignDocUrl();
        } else {

            JSONObject jsonObject = new JSONObject();
            jsonObject.put("fileBase64", signReceiveDto.getDocStr());
            jsonObject.put("fileType", "pdf");
            jsonObject.put("fileName", "");
            JSONObject parseObject = JSON.parseObject(HttpUtil.post(docServerUrl + uploadBase64File, jsonObject.toString()));
            String cd = "code";
            int th = 200;
            if (parseObject.getInteger(cd) == th) {
                signDocumentUrl = parseObject.getJSONObject("data").getString("ossUrl");
                log.info("receiveSignDoc doc url:{}", signDocumentUrl);
            } else {
                log.info("warn receive sign file upload oss fail,result:{}", parseObject.toString());
                throw new BusinessException("文件上传时出现异常-receiveSignDoc");
            }
        }


        caseSourceDocumentRecordUpdate.setDocumentUrlAfterSign(signDocumentUrl);
        caseSourceDocumentRecordUpdate.setDocumentSignstampedStatus(DocumentStatusEnum.CONFIRM_END.getCode());
        //当文书为送达方式及地址确认书更新文书创建时间作为确认时间来使用,后续用于计算有效期限
        ConfigBusiParamDocumentInfo configBusiParamDocumentInfo = configBusiParamDocumentInfoService.getDetailByDocumentCatalogCode(docCategoryCode);
        if (Constant.STRING_KIND_CODE_SDDZQRS.equals(configBusiParamDocumentInfo.getDocumentKindCode())) {
            caseSourceDocumentRecordUpdate.setDocumentCreateTime(LocalDateTime.now());
            //送达地址确认书确认时更新送达地址确认书表的状态为1
        }
        return caseSourceDocumentRecordMapper.updateByPrimaryKeySelective(caseSourceDocumentRecordUpdate);
    }

    /**
     * 【V1.4.1】描述：副流程开始后更新副流程id
     *
     * @author tianrunjia
     * @Date 2022-08-24
     */
    @Override
    public void modCaseDocumentRecordWithAssistStart(String caseId, String catalogCode, String caseAssistId, String caseStageName, String caseStageCode
            , String caseLinkName, String caseLinkCode) {
        caseDocumentRecordMapper.updateCaseDocumentRecordWithAssistStart(caseId, catalogCode, caseAssistId, caseStageName, caseStageCode
                , caseLinkName, caseLinkCode);
    }

    /**
     * 【V1.4.1】描述：根据案件id获取案件阶段的所有有效文书
     *
     * @author tianrunjia
     * @Date 2022-08-24
     */
    @Override
    public List<CaseDocumentCatalogChainDetailVo> doGetAllCaseDocumentInfoEffectiveByCaseId(String caseId) {
        return caseDocumentRecordMapper.selectAllCaseDocumentInfoEffectiveByCaseId(caseId);
    }

    /**
     * 【V1.10.0】描述：根据案件id获取案件详情中案件阶段的所有文书
     *
     * @author tianrunjia
     * @Date 2022-12-11
     */
    @Override
    public List<CaseDocumentRecordInfo> doCaseDetailStageDocumentRecordByCaseId(String caseId, String busiParamId) {
        return caseDocumentRecordMapper.selectCaseDetailStageDocumentRecordByCaseId(caseId, busiParamId);
    }

    /**
     * 获取文书记录以寻找相关文号
     *
     * @param caseId 案件id
     * @return CaseDocumentRecord
     * @author tianrunjia
     * @date 2022-09-04
     **/
    @Override
    public List<CaseDocumentRecord> getCaseDocumentRecordListFindNumSerial(String caseId, String documentCatalogCode) {
        Example example = new Example(CaseDocumentRecord.class);
        example.createCriteria().andEqualTo("caseId", caseId).andEqualTo("documentCatalogCode", documentCatalogCode).andCondition("document_number !='' and document_number is not null")
                //排除修改记录的文书
                .andIsNull("isModifyRecord");
        example.setOrderByClause("document_create_time desc");
        return caseDocumentRecordMapper.selectByExample(example);
    }

    /**
     * 告知书/决定书 关联的补正/更正文书记录（包含撤回和正常状态，不包括修改）
     *
     * @param relationRecordIds   告知书/决定书 文书记录表idList
     * @param documentCatalogCode 补正/更正文书
     * @return CaseDocumentRecord
     **/
    @Override
    public List<CaseDocumentRecord> getCaseCorrectDocumentRecordListFindNum(String caseId, List<String> relationRecordIds, String documentCatalogCode) {
        Example example = new Example(CaseDocumentRecord.class);
        example.createCriteria().andEqualTo("caseId", caseId)
                .andEqualTo("documentCatalogCode", documentCatalogCode)
                .andIn("relationDocumentId", relationRecordIds)
                .andCondition("document_number !='' and document_number is not null and is_modify_record is null");
        example.setOrderByClause("document_create_time desc");
        return caseDocumentRecordMapper.selectByExample(example);
    }

    /**
     * 获取告知书/决定书 有文号的记录（包含撤回和正常状态，不包括修改）
     *
     * @param caseId              案件id
     * @param documentCatalogCode 告知书/决定书
     * @return CaseDocumentRecord
     **/
    @Override
    public List<CaseDocumentRecord> getCaseDocumentRecordHasDocumentNumber(String caseId, String documentCatalogCode) {
        Example example = new Example(CaseDocumentRecord.class);
        example.createCriteria().andEqualTo("caseId", caseId)
                .andEqualTo("documentCatalogCode", documentCatalogCode)
                .andIn("documentRecordStatus", Arrays.asList(DocumentRecordStatusEnum.NORMAL.getCode(), DocumentRecordStatusEnum.WITHDRAW.getCode()))
                .andCondition("document_number !='' and document_number is not null and is_modify_record is null");
        return caseDocumentRecordMapper.selectByExample(example);
    }

    /**
     * 查询涉刑案件可选择文书列表
     *
     * @param caseId 案件id
     * @return {@link List< CaseCriminalTransferFileVo > }
     * @author shishengyao
     * @date 2022/09/29
     */
    @Override
    public List<CaseDocumentRecordCriminalDto> getDocumentRecordOfCriminal(String caseId) {
        List<CaseDocumentRecordCriminalDto> caseDocumentRecordList = caseDocumentRecordMapper.selectCaseDocumentRecordListByCaseId(caseId);
        return caseDocumentRecordList;
    }

    @Override
    public List<CaseDocumentRecordDto> getDocumentRecordDtoList(CaseDocumentRecordQueryDto queryDto) {
        return caseDocumentRecordMapper.selectDocumentRecordDtoList(queryDto);
    }

    @Override
    @WorkFlowRollAnnotation
    @CaseChangeReportData
    @Transactional(rollbackFor = Exception.class)
    public Map<String, Object> receiveHKSignDoc(SignSaveDto signSaveDto) {
        log.info("receiveHKSignDoc start... signSaveDto:{}", signSaveDto);
        SignReturnDto signReturnDto = new SignReturnDto();
        BeanUtils.copyProperties(signSaveDto, signReturnDto);
        signReturnDto.setSignDocUrl(signSaveDto.getSignDocUrl());
        signReturnDto.setSignDeviceType(signReturnDto.getSignDeviceType());
        return receiveSignDoc(signReturnDto);
    }

    /**
     * 查询处罚决定书信息
     *
     * @param caseId
     * @return {@link Map<String, Object> }
     * @author wangfawei
     * @date 2022/12/0
     */
    @Override
    public CaseDocumentRecord getCaseDocumentRecordInfoByCaseId(String caseId) {
        Example example = new Example(CaseDocumentRecord.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("caseId", caseId);
        List<CaseDocumentRecord> recordList = caseDocumentRecordMapper.selectByExample(example);
        if (recordList.size() > 0) {
            return recordList.get(0);
        }
        return null;
    }


    /**
     * 描述: 案件需要在浙里办进行操作的文书
     *
     * @param dto
     * @return com.icinfo.framework.common.web.Result
     * @author zhanghongqiang
     * @Date 2022/12/5
     */
    @Override
    public List<CaseDocumentRecordZlbVo> getCaseDocumentRecordZlb(CaseDocumentRecordZlbDto dto) {
        //通过统一社会信用代码获取当事人信息有效信息
        List<CaseDocumentRecordZlbVo> caseDocumentRecordZlbVos = new ArrayList<>();
        List<CasePartiesAndLegalRecordDto> casePartiesAndLegalRecordDtoList = casePartiesLegalInfoMapper.selectPartiesAndLegalrecord(dto.getUniscid());
        if (ObjectUtils.isEmpty(casePartiesAndLegalRecordDtoList) && casePartiesAndLegalRecordDtoList.size() == 0) {
            return caseDocumentRecordZlbVos;
        }
        // 当事人信息不为空，确认当事人的案件文书信息
        PageHelper.startPage(dto.getPageNum(), dto.getLength());
        List<CaseDocumentRecordZlbVo> list = caseMainInfoMapper.selectcaseAndDocument(casePartiesAndLegalRecordDtoList, dto.getType());
        if (!ObjectUtils.isEmpty(list)) {
            long count = list.stream().filter(i -> !"SIGN_1".equals(i.getDocumentSignstampedStatus())).count();
            CasePartiesAndLegalRecordDto casePartiesAndLegalRecordDto = casePartiesAndLegalRecordDtoList.get(0);
            for (CaseDocumentRecordZlbVo caseDocumentRecordZlbVo : list) {
                // 当事人信息的读取
                ConfigBusiParamDocumentInfo detailByDocumentCatalogCode = configBusiParamDocumentInfoService.getDetailByDocumentCatalogCode(caseDocumentRecordZlbVo.getDocumentCatalogCode());
                String caseId = caseDocumentRecordZlbVo.getCaseId();
                String partyId = caseDocumentRecordZlbVo.getPartyId();
                if (Constant.STRING_1.equals(dto.getType())) {
                    caseDocumentRecordZlbVo.setEntName(casePartiesAndLegalRecordDto.getEntName());
                    caseDocumentRecordZlbVo.setCertificateNo(casePartiesAndLegalRecordDto.getUniscid());
                    String identityType = casePartiesAndLegalRecordDto.getIdentityType();
                    if (StringUtils.isBlank(identityType)) {
                        caseDocumentRecordZlbVo.setIdentityType("统一社会信用代码");
                    } else {
                        caseDocumentRecordZlbVo.setIdentityType(CertTypeEnum.getValueByCode(identityType));
                    }
                    Example queryExample = new Example(CaseDocumentSendinfoConfirm.class);
                    Example.Criteria criteria = queryExample.createCriteria();
                    criteria.andEqualTo("caseId", caseId).andEqualTo("partyId", partyId);
                    List<CaseDocumentSendinfoConfirm> sendInfoConfirmList
                            = caseDocumentSendinfoConfirmMapper.selectByExample(queryExample);
                    if (!ObjectUtils.isEmpty(sendInfoConfirmList) && sendInfoConfirmList.size() > 0) {
                        //这里不是空的(取出送达地址确认书的的目录编码)
                        CaseDocumentSendinfoConfirm caseDocumentSendinfoConfirm = sendInfoConfirmList.get(0);
                        String documentCatalogCode = caseDocumentSendinfoConfirm.getDocumentCatalogCode();
                        String pickMobile = caseDocumentSendinfoConfirm.getPickMobile();
                        if (StringUtils.isNotBlank(pickMobile)) {
                            caseDocumentRecordZlbVo.setModeOfService(Constant.STRING_2);
                        } else {
                            caseDocumentRecordZlbVo.setModeOfService(Constant.STRING_1);
                        }
                        caseDocumentRecordZlbVo.setMobile(caseDocumentSendinfoConfirm.getMobile());
                        caseDocumentRecordZlbVo.setPickMobile(caseDocumentSendinfoConfirm.getPickMobile());
                        caseDocumentRecordZlbVo.setSendAddress(caseDocumentSendinfoConfirm.getSendAddress());
                        caseDocumentRecordZlbVo.setPostCode(caseDocumentSendinfoConfirm.getPostCode());
                        caseDocumentRecordZlbVo.setPickPerson(caseDocumentSendinfoConfirm.getPickPerson());
                        if (StringUtils.isNotBlank(documentCatalogCode)) {
                            Example documentExample = new Example(CaseDocumentRecord.class);
                            documentExample.createCriteria().andEqualTo("caseId", caseId)
                                    .andEqualTo("documentCatalogCode", documentCatalogCode)
                                    .andEqualTo("partyId", partyId).andEqualTo("documentRecordStatus", Constant.STRING_1);
                            List<CaseDocumentRecord> caseDocumentRecords = caseDocumentRecordMapper.selectByExample(documentExample);
                            if (!ObjectUtils.isEmpty(caseDocumentRecords) && caseDocumentRecords.size() > 0) {
                                CaseDocumentRecord caseDocumentRecord = caseDocumentRecords.get(0);
                                caseDocumentRecordZlbVo.setConfirmDocumentId(caseDocumentRecord.getId());
                                caseDocumentRecordZlbVo.setConfirmDocumentCatalogCode(caseDocumentRecord.getDocumentCatalogCode());
                                caseDocumentRecordZlbVo.setFillInStatus(caseDocumentRecord.getDocumentSignstampedStatus());
                                caseDocumentRecordZlbVo.setDocumentSendUrl(caseDocumentRecord.getDocumentUrlAfterSign());
                            }
                        }
                    }
                    // 当前案件当前人有一个送达成功的就不能在修改送达地址确认书
                    //modifyShow
                    Example documentExampleTwo = new Example(CaseDocumentRecord.class);
                    documentExampleTwo.createCriteria().andEqualTo("caseId", caseId)
                            .andEqualTo("documentSentStatus", "SEND_1")
                            .andEqualTo("partyId", partyId).andEqualTo("documentRecordStatus", Constant.STRING_1);
                    List<CaseDocumentRecord> caseDocumentRecords = caseDocumentRecordMapper.selectByExample(documentExampleTwo);
                    if (!ObjectUtils.isEmpty(caseDocumentRecords) && caseDocumentRecords.size() > 0) {
                        caseDocumentRecordZlbVo.setModifyShow(Constant.STRING_1);
                    }
                } else {
                    // 这里加入决定书只是为了验收需求，后期可从新设计去掉（缴款）(签字确认)
                    // 加入告知书的也要特殊处理 为了验收需求
                    if (caseDocumentRecordZlbVo.getDocumentCatalogCode().contains("CFGZS00")) {
                        if (StringUtils.isBlank(caseDocumentRecordZlbVo.getDocumentSignstampedStatus())) {
                            caseDocumentRecordZlbVo.setDocumentSignstampedStatus("SIGN_3");
                        }
                        caseDocumentRecordZlbVo.setZlbSignTime(caseDocumentRecordZlbVo.getDocumentApprovalTime());
                    }
                    if (caseDocumentRecordZlbVo.getDocumentCatalogCode().contains("CFJDS00")) {
                        if (StringUtils.isBlank(caseDocumentRecordZlbVo.getDocumentSignstampedStatus())) {
                            caseDocumentRecordZlbVo.setDocumentSignstampedStatus("SIGN_3");
                        }
                        caseDocumentRecordZlbVo.setZlbSignTime(caseDocumentRecordZlbVo.getDocumentApprovalTime());
                        //查询缴款信息  case_payment_main_record
                        Example example = new Example(CasePaymentMainRecord.class);
                        example.createCriteria().andEqualTo("caseId", caseId)
                                .andEqualTo("partyId", partyId);
                        List<CasePaymentMainRecord> casePaymentMainRecords = casePaymentMainRecordMapper.selectByExample(example);
                        if (!ObjectUtils.isEmpty(casePaymentMainRecords) && casePaymentMainRecords.size() > 0) {
                            CasePaymentMainRecord casePaymentMainRecord = casePaymentMainRecords.get(0);
                            // case_payment_result_record
                            String noticeNo = casePaymentMainRecord.getNoticeNo();
                            Example exampleResult = new Example(CasePaymentResultRecord.class);
                            exampleResult.createCriteria().andEqualTo("caseId", caseId).andEqualTo("noticeNo", noticeNo);
                            List<CasePaymentResultRecord> casePaymentResultRecords = casePaymentResultRecordMapper.selectByExample(exampleResult);
                            if (ObjectUtils.isEmpty(casePaymentResultRecords) && casePaymentResultRecords.size() == 0) {
                                // 没有未缴款记录，设置未缴款，显示缴款按钮
                                caseDocumentRecordZlbVo.setWhetherToPay(Constant.STRING_1);
                                String qrKeyInfo = paymentUrl + "?jkdh=" + noticeNo + "&id=" + paymentId;
                                caseDocumentRecordZlbVo.setToPayUrl(qrKeyInfo);
                            } else {
                                caseDocumentRecordZlbVo.setWhetherToPay(Constant.STRING_2);
                            }
                        }

                    }
                }
                String documentCatalogName = "";
                if (!ObjectUtils.isEmpty(detailByDocumentCatalogCode)) {
                    documentCatalogName = detailByDocumentCatalogCode.getDocumentCatalogName();
                }
                caseDocumentRecordZlbVo.setConfirmedCount(count);
                caseDocumentRecordZlbVo.setDocumentName(documentCatalogName);
                caseDocumentRecordZlbVo.setDocumentDesc(caseDocumentRecordZlbVo.getCaseOrgName() + "于" +
                        caseDocumentRecordZlbVo.getZlbSignTime() + "发送的" + documentCatalogName);
                caseDocumentRecordZlbVo.setRouteUrl("/doc-service-sign?tab=tab02&uniscid=" + dto.getUniscid());
            }
        }
        return list;
    }

    @Override
    public Map<String, Object> getZlbCaseConfirmPreview(CaseConfirmPreviewDto caseConfirmPreviewDto) {
        if (StringUtils.isBlank(caseConfirmPreviewDto.getPickMobile())
                && StringUtils.isBlank(caseConfirmPreviewDto.getMobile())) {
            throw new BusinessException("必须选择一种送达方式");
        }
        String caseId = caseConfirmPreviewDto.getCaseId();
        String documentCatalogCode = caseConfirmPreviewDto.getDocumentCatalogCode();
        // 送达地址确认书的id
        String documentId = caseConfirmPreviewDto.getDocumentId();
        String sendDocumentId = caseConfirmPreviewDto.getSendDocumentId();
        CaseDocumentRecord caseDocumentRecordStatus = caseDocumentRecordMapper.selectByPrimaryKey(sendDocumentId);
        if (!ObjectUtils.isEmpty(caseDocumentRecordStatus)) {
            String documentRecordStatus = caseDocumentRecordStatus.getDocumentRecordStatus();
            if (!Constant.STRING_1.equals(documentRecordStatus)) {
                throw new BusinessException("文书已经被撤回");
            }
        }
        CaseDocumentRecord caseDocumentRecordSend = caseDocumentRecordMapper.selectByPrimaryKey(documentId);
        if (!ObjectUtils.isEmpty(caseDocumentRecordSend)) {
            String documentRecordStatus = caseDocumentRecordSend.getDocumentRecordStatus();
            String documentSentStatus = caseDocumentRecordSend.getDocumentSentStatus();
            if (!Constant.STRING_1.equals(documentRecordStatus)) {
                throw new BusinessException("文书已经被撤回");
            }
            if ("SEND_1".equals(documentSentStatus)) {
                throw new BusinessException("文书已被送达");
            }
        }
        CaseMainInfoVo caseMainInfo = caseMainInfoService.getCaseMainInfo(caseId);
        // 当事人id
        String partyId = caseConfirmPreviewDto.getPartyId();
        //增加送达当事人id处理
        if (ObjectUtils.isEmpty(partyId)) {
            String casePartiesReasonType = caseMainInfo.getCasePartiesReasonType();
            if (ObjectUtils.isEmpty(partyId)) {
                if (PartiesReasonTypeEnum.MULTIPLE_PARTIES.getCode().equals(casePartiesReasonType)) {
                    throw new BusinessException("多当事人时送达流程指定当事人id");
                }
            }
            Map<String, String> map = casePartiesRecordService.getCasePartyIdNameInfo(caseId);
            partyId = map.get("partyId");
        }
        // 别的送达地址确认书对应字段
        /*SDDZQRS_DH: "   15933336666"
        SDDZQRS_DZ: "   阿达"
        SDDZQRS_SJHM: "15988887777"
        SDDZQRS_SJR: "个人当事人"
        SDDZQRS_YB: "大大"*/
        Map<String, Object> map = new HashMap<>();
        StageDocCommonPreviewDto saveDto = new StageDocCommonPreviewDto();
        StageDocCommonHtmlRequest request = new StageDocCommonHtmlRequest();
        request.setCaseId(caseId);
        request.setDocumentCatalogCode(documentCatalogCode);
        request.setDocumentId(sendDocumentId);
        request.setPartyId(partyId);
        DocumentCommonFormDataVo commonDocumentFormData = stageDocCommonOperateService.getCommonDocumentFormData(request);
        HashMap innerMap = BaseUtil.javaToMap(commonDocumentFormData.getDataMap());
        HashMap dataMap = (HashMap) innerMap.get("innerMap");
        if (ObjectUtils.isEmpty(dataMap)) {
            throw new BusinessException("未获取到待填写文书数据可能已经被删除");
        }
        dataMap.put("SDDZQRS_DZ", caseConfirmPreviewDto.getSendAddress());
        dataMap.put("SDDZQRS_YB", caseConfirmPreviewDto.getPostCode());
        dataMap.put("SDDZQRS_SJHM", caseConfirmPreviewDto.getMobile());
        dataMap.put("SDDZQRS_DH", caseConfirmPreviewDto.getPickMobile());
        if (StringUtils.isNotBlank(caseConfirmPreviewDto.getPickPerson())) {
            dataMap.put("SDDZQRS_SJR", caseConfirmPreviewDto.getPickPerson());
        }
        saveDto.setDataMap(dataMap);
        saveDto.setDocumentCatalogCode(documentCatalogCode);
        Map<String, Object> previewDocMap = stageDocCommonOperateService.genPreviewDoc(saveDto);
        String status = MapUtils.getString(previewDocMap, "success", "");
        if ("true".equals(status)) {
            map.put("msg", MapUtils.getString(previewDocMap, "msg", ""));
            map.put("code", "success");
            map.put("fileUrl", MapUtils.getString(previewDocMap, "pdfUrl", ""));
        } else {
            map.put("msg", MapUtils.getString(previewDocMap, "msg", ""));
            map.put("code", "error");
        }
        //预览的时候更新数据，为以后的签字做准备
        Example updateExample = new Example(CaseDocumentSendinfoConfirm.class);
        updateExample.createCriteria().andEqualTo("caseId", caseId).andEqualTo("partyId", partyId);
        CaseDocumentSendinfoConfirm caseDocumentSendinfoConfirm = new CaseDocumentSendinfoConfirm();
        caseDocumentSendinfoConfirm.setSendAddress(caseConfirmPreviewDto.getSendAddress());
        caseDocumentSendinfoConfirm.setPostCode(caseConfirmPreviewDto.getPostCode());
        caseDocumentSendinfoConfirm.setMobile(caseConfirmPreviewDto.getMobile());
        caseDocumentSendinfoConfirm.setPickMobile(caseConfirmPreviewDto.getPickMobile());
        if (StringUtils.isNotBlank(caseConfirmPreviewDto.getPickPerson())) {
            caseDocumentSendinfoConfirm.setPickPerson(caseConfirmPreviewDto.getPickPerson());
        }
        caseDocumentSendinfoConfirmMapper.updateByExampleSelective(caseDocumentSendinfoConfirm, updateExample);
        CaseDocumentRecord caseDocumentRecord = new CaseDocumentRecord();
        caseDocumentRecord.setDocumentContent(JSON.toJSONString(dataMap));
        Example updateDocumentExample = new Example(CaseDocumentRecord.class);
        updateDocumentExample.createCriteria().andEqualTo("id", sendDocumentId)
                //.andNotEqualTo("documentRecordStatus", DocumentRecordStatusEnum.WITHDRAW.getCode());
                .andIn("documentRecordStatus", Arrays.asList(DocumentRecordStatusEnum.NORMAL.getCode(), DocumentRecordStatusEnum.DRAFT.getCode()));
        caseDocumentRecordMapper.updateByExampleSelective(caseDocumentRecord, updateDocumentExample);
        return map;
    }


    @Override
    @WorkFlowRollAnnotation
    @CaseChangeReportData
    @Transactional(rollbackFor = Exception.class)
    public Map<String, Object> receiveZlbSignDoc(SignReturnDto signReceiveDto) {
        log.info("receiveSignDoc start... signReceiveDto:{}", signReceiveDto);
        if (ObjectUtils.isEmpty(signReceiveDto)) {
            throw new BusinessException("未指定文书案件相关信息");
        }
        String caseId = signReceiveDto.getCaseId();
        if (ObjectUtils.isEmpty(caseId)) {
            throw new BusinessException("未指定案件id");
        }
        String docCategoryCode = signReceiveDto.getDocCategoryCode();
        if (ObjectUtils.isEmpty(docCategoryCode)) {
            throw new BusinessException("未指定文书目录编码");
        }

        String partyId = signReceiveDto.getPartyId();
        String partyName = "";
        String documentCatalogCode = signReceiveDto.getDocCategoryCode();
        CaseMainInfoVo caseMainInfo = caseMainInfoService.getCaseMainInfo(caseId);
        String partiesReasonType = caseMainInfo.getCasePartiesReasonType();
        String handleType = caseMainInfo.getHandleType();

        //查询文书种类
        List<ConfigBusiParamDocumentInfo> configList = configBusiParamDocumentInfoService.getDocumentConfigInfoByDocumentCatalogCode(caseId, caseMainInfo, documentCatalogCode);
        String kindCode;
        if (!ObjectUtils.isEmpty(configList)) {
            kindCode = configList.get(Constant.INTEGER_0).getDocumentKindCode();
        } else {
            throw new BusinessException("未匹配文书种类编码信息-caseId:" + caseId + ",documentCatalogCode:" + documentCatalogCode);
        }
        //增加送达当事人id处理
        if (ObjectUtils.isEmpty(partyId)) {
            if (PartiesReasonTypeEnum.MULTIPLE_PARTIES.getCode().equals(partiesReasonType)
                    && !"GZSHZ".equals(kindCode)
            ) {
                throw new BusinessException("多当事人案件需指定当事人id");
            }
            Map<String, String> map = casePartiesRecordService.getCasePartyIdNameInfo(caseId);
            partyId = map.get("partyId");
            partyName = map.get("partyName");
        }
        CaseDocumentRecord caseDocumentRecordUpdate = getCaseDocumentRecord(caseId, docCategoryCode, partyId);
        if (caseDocumentRecordUpdate == null) {
            log.error("未匹配到文书记录-receiveSignDoc,caseId:{},partyId:{},documentCatalogCode:{}", caseId, partyId, documentCatalogCode);
            throw new BusinessException("未匹配到文书记录-receiveSignDoc");
        }
        // 处罚决定书比较特殊，不走流程，但是为了演示需要签字确认
        /*if (Constant.STRING_KIND_CODE_CFJDS.equals(kindCode)) {
            CaseDocumentRecord caseDocumentRecord = new CaseDocumentRecord();
            caseDocumentRecord.setId(caseDocumentRecordUpdate.getId());
            caseDocumentRecord.setDocumentSignstampedStatus("SIGN_1");
            caseDocumentRecordMapper.updateByPrimaryKeySelective(caseDocumentRecord);
            throw new BusinessException("签字完成");
        }*/
        caseDocumentRecordUpdate.setSignTime(LocalDateTime.now());
        // 将我们的文书和签字组成一个签过字的文书
        String documentContent = caseDocumentRecordUpdate.getDocumentContent();
        JSONObject jsonObject = JSON.parseObject(documentContent);
        jsonObject.put("ZLB_QM", signReceiveDto.getDocStr());
        jsonObject.put("signTime", LocalDate.now().format(DateTimeFormatter.ofPattern("yyyy年M月d日")));
        FillAndConvertToPdfRequest pdfRequest = new FillAndConvertToPdfRequest();
        pdfRequest.setTemplateCode(configList.get(0).getTemplateLegalCode());
        pdfRequest.setParamMap(jsonObject);
        Map<String, String> pdfUrl = stageDocCommonOperateService.getConvertedPdfUrl(pdfRequest);
        if (ObjectUtil.isEmpty(pdfUrl)) {
            throw new BusinessException("获取文书失败！");
        }
        System.out.println(pdfUrl.get("fileUrl"));
        caseDocumentRecordUpdate.setDocumentUrlAfterSign(pdfUrl.get("fileUrl"));
        caseDocumentRecordUpdate.setDocumentSignstampedStatus(DocumentStatusEnum.CONFIRM_END.getCode());
        //当文书为送达方式及地址确认书更新文书创建时间作为确认时间来使用,后续用于计算有效期限
        ConfigBusiParamDocumentInfo configBusiParamDocumentInfo = configBusiParamDocumentInfoService.getDetailByDocumentCatalogCode(docCategoryCode);
        if (Constant.STRING_KIND_CODE_SDDZQRS.equals(configBusiParamDocumentInfo.getDocumentKindCode())) {
            caseDocumentRecordUpdate.setDocumentCreateTime(LocalDateTime.now());
            //送达地址确认书确认时更新送达地址确认书表的状态为1
            Example updateExample = new Example(CaseDocumentSendinfoConfirm.class);
            updateExample.createCriteria().andEqualTo("caseId", caseDocumentRecordUpdate.getCaseId()).andEqualTo("partyId", caseDocumentRecordUpdate.getPartyId());
            CaseDocumentSendinfoConfirm caseDocumentSendinfoConfirm = new CaseDocumentSendinfoConfirm();
            caseDocumentSendinfoConfirm.setStatus(Constant.INTEGER_1);
            caseDocumentSendinfoConfirmMapper.updateByExampleSelective(caseDocumentSendinfoConfirm, updateExample);
        }
        // 签字之后判断案件是否需要，更新案件状态,查询配置表
        Map<String, Object> rs = new HashMap<>(8);
        if (this.caseDocumentRecordMapper.updateByPrimaryKeySelective(caseDocumentRecordUpdate) == 1) {
            rs.put("workId", caseId);
            rs.put("closeSignal", "CLOSE-TRIGGER-SIGNSTAMPED");
            if (!ObjectUtils.isEmpty(partyId)) {
                if (!ObjectUtils.isEmpty(configList)) {
                    if (sentRelatedNeedPartyIdDocumentKindCodeList.contains(kindCode)) {
                        rs.put("workSubId", partyId);
                    }
                }
                if (Constant.STRING_2.equals(handleType)) {
                    rs.put("workSubId", partyId);
                } else {
                    rs.put("workSubId", null);
                }
            }
            if (!ObjectUtils.isEmpty(documentCatalogCode) && documentCatalogCode.contains(Constant.STRING_UNDERLINE)) {
                //查询送达回证配置
                ConfigBusiParamDocumentInfo detailByDocumentCatalogCode = configBusiParamDocumentInfoService.getDetailByDocumentCatalogCode(documentCatalogCode);
                documentCatalogCode = detailByDocumentCatalogCode.getMatchSentDocumentCatalogCode();
                if (ObjectUtils.isEmpty(documentCatalogCode)) {
                    throw new BusinessException("未找到对应更新文书目录编码-receiveSignDoc");
                }

                //更新文书送达时间
                String sendStatus = DocumentSendStatusEnum.SEND_SUCCESS.getCode();
                CaseDocumentRecordQueryDto queryDto = new CaseDocumentRecordQueryDto();
                queryDto.setCaseId(caseId);
                queryDto.setRelateDocumentCatalogCode(documentCatalogCode);
                if (!HandleTypeEnum.MERGE_PUNISH.getCode().equals(handleType)) {
                    queryDto.setPartyId(partyId);
                }
                CaseDocumentRecordDetailVo vo = getCaseDocumentRecordDetail(queryDto);
                if (ObjectUtils.isEmpty(vo)) {
                    throw new BusinessException("未找到文书记录-caseId:{" + caseId + "},documentCatalogCode:{" + documentCatalogCode + "}");
                }
                rs.put("closeSignal", "CLOSE-TRIGGER-SENT");
                caseDocumentRecordService.updateDocumentSentInfo(vo.getDocumentId(), LocalDateTime.now(), sendStatus);
            } else {
                List<String> list = new ArrayList<>();
                list.add("CFGZS");
                list.add("CFGZSTZL");
                list.add("CFJDS");
                list.add("BYCFJDS");
                if (list.contains(kindCode)) {
                    //取对应审批表
                    rs.put("closeSignal", "CLOSE-TRIGGER-SENT");
                }
            }
            // 浙政钉消息发送
            if (Constant.STRING_KIND_CODE_SDDZQRS.equals(configBusiParamDocumentInfo.getDocumentKindCode())) {
                sendZlbDingMsg(caseId, documentCatalogCode, caseMainInfo.getCaseNumber(), partyName, 1);
            } else {
                sendZlbDingMsg(caseId, documentCatalogCode, caseMainInfo.getCaseNumber(), partyName, 2);
            }
            rs.put("documentCatalogCode", documentCatalogCode);
        } else {
            throw new BusinessException("更新文书信息时出现异常");
        }
        return rs;
    }

    /**
     * 新审批 审批人钉钉消息（新加--兼容发送管理人员的政务钉钉信息）
     *
     * @param caseId
     * @param documentCatalogCode
     * @param type
     */
    private void sendZlbDingMsg(String caseId, String documentCatalogCode, String caseNumber, String name, Integer type) {
        //获取执法人员和领导的政务钉钉id
        List<CaseHandlePersonRecordVo> handlePersonRecordVos = caseHandlePersonRecordService.getCaseHandlePersonRecordListByCaseId(caseId);
        if (!handlePersonRecordVos.isEmpty()) {
            for (CaseHandlePersonRecordVo handlePersonRecordVo : handlePersonRecordVos) {
                if (type == 1) {
                    this.sendDingMsg(caseId, documentCatalogCode, caseNumber, name, handlePersonRecordVo.getDingId(), "zlbServiceMsg");
                } else {
                    this.sendDingMsg(caseId, documentCatalogCode, caseNumber, name, handlePersonRecordVo.getDingId(), "zlbSignMsg");
                }
            }
        }
    }

    /**
     * 发送钉钉消息
     *
     * @param caseId              案件ID
     * @param documentCatalogCode 文书目录
     * @param caseNumber          案件编号
     * @param zwdingAccountId     政务钉钉ID
     * @param dingMsgType         消息类型：auditPass（审核通过），auditRetired（审核退回），newAudit（新的审批）
     */
    private void sendDingMsg(String caseId, String documentCatalogCode, String caseNumber, String name, String zwdingAccountId, String dingMsgType) {
        try {
            ConfigBusiParamDocumentInfo configBusiParamDocumentInfo = configBusiParamDocumentInfoService.getDetailByDocumentCatalogCode(documentCatalogCode);
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("caseId", caseId);
            jsonObject.put("documentCatalogCode", documentCatalogCode);
            jsonObject.put("caseNumber", caseNumber);
            jsonObject.put("partyName", name);
            jsonObject.put("documentCatalogName", configBusiParamDocumentInfo.getDocumentCatalogName());
            jsonObject.put("dingDingId", zwdingAccountId);
            jsonObject.put("url", "");
            jsonObject.put("dingMsgType", dingMsgType);
            BaseUtil.post(dingSendUrl, jsonObject);
        } catch (Exception e) {
            log.error("-----------发送钉钉消息失败，caseId：{}, 消息类型：{}--------------", caseId, dingMsgType, e);
        }
    }

    @Override
    public int sendZlbSignDoc(sendSignDocZlbDto saveDto) {
        String receiverAccount = saveDto.getReceiverAccount();
        if (cfRedisRepository.exists(RedisUtil.REDIS_PREFIX_ZLB + receiverAccount)) {
            throw new BusinessException("需间隔一分钟，请勿频繁操作");
        }
        String receiverName = saveDto.getReceiverName();
        String documentId = saveDto.getDocumentId();
        String content = documentSentFlowService.assembleSmsContentProvince(receiverAccount, receiverName, documentId, Constant.STRING_2);
        String sendResult = documentSentFlowService.sendSmsProvince(receiverAccount, content, "");
        if (!ObjectUtils.isEmpty(sendResult)) {
            throw new BusinessException(Constant.STRING_FAIL_CH);
        } else {
            //短信发送成功更新送达记录
            cfRedisRepository.setExpire(RedisUtil.REDIS_PREFIX_ZLB + receiverAccount, receiverAccount, 60);
            CaseDocumentRecord caseDocumentRecord = new CaseDocumentRecord();
            caseDocumentRecord.setId(documentId);
            caseDocumentRecord.setZlbSign(Constant.STRING_1);
            caseDocumentRecord.setZlbSignPhone(receiverAccount);
            caseDocumentRecord.setZlbSignPhone(receiverName);
            caseDocumentRecord.setZlbSignTime(DateUtil.dateToLocalDateTime(new Date()));
            caseDocumentRecord.setDocumentSignstampedStatus(DocumentStatusEnum.WAIT_TO_SIGN_ZLB.getCode());
            return caseDocumentRecordMapper.updateByPrimaryKeySelective(caseDocumentRecord);
        }
    }

    @Override
    public Result<String> modZlbCaseConfirm(CaseConfirmPreviewDto caseConfirmPreviewDto) {
        String caseId = caseConfirmPreviewDto.getCaseId();
        String documentCatalogCode = caseConfirmPreviewDto.getDocumentCatalogCode();
        String documentId = caseConfirmPreviewDto.getDocumentId();
        String sendDocumentId = caseConfirmPreviewDto.getSendDocumentId();
        CaseDocumentRecord caseDocumentRecordStatus = caseDocumentRecordMapper.selectByPrimaryKey(documentId);
        if (!ObjectUtils.isEmpty(caseDocumentRecordStatus)) {
            String documentRecordStatus = caseDocumentRecordStatus.getDocumentRecordStatus();
            if (!Constant.STRING_1.equals(documentRecordStatus)) {
                throw new BusinessException("文书已经被撤回");
            }
        }
        CaseDocumentRecord caseDocumentRecordSend = caseDocumentRecordMapper.selectByPrimaryKey(sendDocumentId);
        if (!ObjectUtils.isEmpty(caseDocumentRecordSend)) {
            String documentRecordStatus = caseDocumentRecordSend.getDocumentRecordStatus();
            String documentSentStatus = caseDocumentRecordSend.getDocumentSentStatus();
            if (!Constant.STRING_1.equals(documentRecordStatus)) {
                throw new BusinessException("文书已经被撤回");
            }
            if ("SEND_1".equals(documentSentStatus)) {
                throw new BusinessException("文书已被送达");
            }
        }
        CaseMainInfoVo caseMainInfo = caseMainInfoService.getCaseMainInfo(caseId);
        // 当事人id
        String partyId = caseConfirmPreviewDto.getPartyId();
        //增加送达当事人id处理
        if (ObjectUtils.isEmpty(partyId)) {
            String casePartiesReasonType = caseMainInfo.getCasePartiesReasonType();
            if (ObjectUtils.isEmpty(partyId)) {
                if (PartiesReasonTypeEnum.MULTIPLE_PARTIES.getCode().equals(casePartiesReasonType)) {
                    throw new BusinessException("多当事人时送达流程指定当事人id");
                }
            }
            Map<String, String> map = casePartiesRecordService.getCasePartyIdNameInfo(caseId);
            partyId = map.get("partyId");
        }
        StageDocCommonHtmlRequest request = new StageDocCommonHtmlRequest();
        request.setCaseId(caseId);
        request.setDocumentCatalogCode(documentCatalogCode);
        request.setDocumentId(documentId);
        request.setPartyId(partyId);
        DocumentCommonFormDataVo commonDocumentFormData = stageDocCommonOperateService.getCommonDocumentFormData(request);
        HashMap innerMap = BaseUtil.javaToMap(commonDocumentFormData.getDataMap());
        HashMap dataMap = (HashMap) innerMap.get("innerMap");
        if (ObjectUtils.isEmpty(dataMap)) {
            throw new BusinessException("未获取到待填写文书数据可能已经被删除");
        }
        dataMap.put("SDDZQRS_DZ", caseConfirmPreviewDto.getSendAddress());
        dataMap.put("SDDZQRS_YB", caseConfirmPreviewDto.getPostCode());
        dataMap.put("SDDZQRS_SJHM", caseConfirmPreviewDto.getMobile());
        dataMap.put("SDDZQRS_DH", caseConfirmPreviewDto.getPickMobile());
        if (StringUtils.isNotBlank(caseConfirmPreviewDto.getPickPerson())) {
            dataMap.put("SDDZQRS_SJR", caseConfirmPreviewDto.getPickPerson());
        }
        StageDocCommonOperateSaveDto saveDto = new StageDocCommonOperateSaveDto();
        saveDto.setPartyId(partyId);
        saveDto.setDocumentCatalogCode(documentCatalogCode);
        saveDto.setBelongDocumentId(documentId);
        saveDto.setCaseId(caseId);
        saveDto.setDataMap(dataMap);
        Map<String, Object> resultMap = stageDocCommonOperateService.saveDocInfo(saveDto);
        String status = MapUtils.getString(resultMap, "success", "");
        if ("true".equals(status)) {
            return Result.success("修改成功");
        } else {
            return Result.error("修改失败");
        }
    }

    /**
     * 【1.9.4】描述：专题查询-文书查询
     *
     * @param dto {@link CaseDocumentPageDto}
     * @return {@link List<PageCaseDocumentVo>}
     * @author cds
     * @date 2022/12/9
     * @version 1.9.4
     */
    @Override
    public List<PageCaseDocumentVo> pageCaseDocumentRecord(CaseDocumentPageDto dto) {
        this.checkOrgCode(dto);
        PageHelper.startPage(dto.getPageNum(), dto.getLength());

        //查询办案直通车的历史文书
        if (StrUtil.equals("0", dto.getDocumentSource())) {
            List<PageCaseDocumentVo> pageCaseDocumentVos = appCaseBeforeDocumentRecordMapper.pageAppDocumentRecord(dto);
            pageCaseDocumentVos.forEach(vo -> {
                CasePartiesInfoVo casePartiesInfoVo = new CasePartiesInfoVo();
                casePartiesInfoVo.setPartyName(vo.getPersonName());
                casePartiesInfoVo.setPartyId(vo.getPartyId());
                vo.setCasePartiesList(Arrays.asList(casePartiesInfoVo));
            });
            return pageCaseDocumentVos;
        }

        List<PageCaseDocumentVo> documentList = caseDocumentRecordMapper.pageCaseDocumentRecord(dto);

        // 批量查询当事人列表
        if (CollUtil.isNotEmpty(documentList)) {
            Set<String> caseIds = documentList.stream().map(PageCaseDocumentVo::getCaseId).collect(Collectors.toSet());
            Map<String, List<CasePartiesInfoVo>> caseIdMap = casePartiesRecordService.listCasePartiesRecordByCaseIds(caseIds);
            for (PageCaseDocumentVo caseDocumentVo : documentList) {
                caseDocumentVo.setCasePartiesList(caseIdMap.get(caseDocumentVo.getCaseId()));
            }
        }

        return documentList;
    }

    /**
     * 案件移送文书列表
     *
     * @param caseId 案件id
     * @return java.util.List<com.icinfo.cloud.provider.punish.ucase.casemain.dto.CaseDocumentRecordCriminalDto>
     * @author liuyongfei
     * @date 2022/12/15
     */
    @Override
    public List<CaseDocumentRecordCriminalDto> getTransferDocumentRecordOfCriminal(String caseId) {
        return caseDocumentRecordMapper.selectTransferCaseDocumentRecordListByCaseId(caseId);
    }

    /**
     * 【V1.10.0】描述：APP端签字捺印案件流程滚动
     *
     * @param
     * @return
     * @author tianrunjia
     */
    @WorkFlowRollAnnotation
    @CaseChangeReportData
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Map<String, Object> doCaseRollByAppSignDoc(String caseId, String documentCatalogCode) {

        Map<String, Object> rs = new HashMap<>();

        rs.put("workId", caseId);
        rs.put("closeSignal", "CLOSE-TRIGGER-SIGNSTAMPED");
        rs.put("documentCatalogCode", documentCatalogCode);
        System.out.println("================================:" + documentCatalogCode);
        ConfigBusiParamDocumentInfo configBusiParamDocumentInfo = configBusiParamDocumentInfoService.getDetailByDocumentCatalogCode(documentCatalogCode);
        //处理送达回证的送达文书已送达
        dealSdhzMatchDocumentSendSuccess(caseId, documentCatalogCode, configBusiParamDocumentInfo);
        return rs;
    }

    /**
     * 处理送达回证的送达文书已送达
     *
     * @param caseId                      案件id
     * @param documentCatalogCode         送达回证的文书目录编码
     * @param configBusiParamDocumentInfo 送达回证的文书参数配置
     */
    private void dealSdhzMatchDocumentSendSuccess(String caseId, String documentCatalogCode, ConfigBusiParamDocumentInfo configBusiParamDocumentInfo) {
        if (!DocumentKindEnum.DOC_KIND_SDHZ.getCode().equals(configBusiParamDocumentInfo.getDocumentKindCode())) {
            return;
        }
        //送达回证 确认后调用服务判断是否标记送达
        String originDocumentCatalogCode = configBusiParamDocumentInfo.getMatchSentDocumentCatalogCode();
        if (ObjectUtils.isEmpty(originDocumentCatalogCode)) {
            throw new BusinessException(String.format("未找到送达回证[%s]对应送达文书目录编码", documentCatalogCode));
        }
        CaseDocumentRecordQueryDto queryDto = new CaseDocumentRecordQueryDto();
        queryDto.setCaseId(caseId);
        queryDto.setRelateDocumentCatalogCode(originDocumentCatalogCode);
        CaseDocumentRecordDetailVo originDocumentRecord = getCaseDocumentRecordDetail(queryDto);
        if (ObjectUtils.isEmpty(originDocumentRecord)) {
            throw new BusinessException("未找到文书记录-caseId:{" + caseId + "},documentCatalogCode:{" + originDocumentCatalogCode + "}");
        }
        //流程滚动
        SentFlowRollInfoSaveDto sendFlowRollInfo = new SentFlowRollInfoSaveDto();
        sendFlowRollInfo.setCaseId(caseId);
        sendFlowRollInfo.setPartyId(originDocumentRecord.getPartyId());
        sendFlowRollInfo.setDocumentCatalogCode(documentCatalogCode);
        documentSentFlowService.sentFlowRoll(sendFlowRollInfo);
        if (documentSentFlowService.checkDocumentIsAllSend(caseId, originDocumentRecord.getDocumentId())) {
            //更新待送达文书为已送达
            caseDocumentRecordService.updateDocumentSentInfo(originDocumentRecord.getDocumentId(),
                    LocalDateTime.now(), DocumentSendStatusEnum.SEND_SUCCESS.getCode());
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public DocumentRecordModifyReturnVo modifyDocumentRecord(DocumentRecordModifyDto saveDto) {
        CustomCheckParamUtil.doCheck(saveDto);
        String originalDocument = saveDto.getDocumentId();
        String caseId = saveDto.getCaseId();
        CaseDocumentRecord caseDocumentRecordInfo = caseDocumentRecordMapper.selectByPrimaryKey(originalDocument);
        if (ObjectUtil.isEmpty(caseDocumentRecordInfo)) {
            throw new BusinessException("文书记录不存在");
        }
        UserDTO userInfo = UserUtil.getUserInfo();
        if (userInfo == null) {
            throw new BusinessException("未登录或登录信息已失效");
        }
        Map<String, Object> dataMap = saveDto.getDataMap();
        // 文书记录修改变更的字段
        JSONObject jsonObject = JSON.parseObject(caseDocumentRecordInfo.getDocumentContent());
        for (Map.Entry<String, Object> entry : jsonObject.entrySet()) {
            if (ObjectUtil.isNotEmpty(dataMap.get(entry.getKey())) && entry.getValue() != null && !entry.getValue().equals(dataMap.get(entry.getKey()))) {
                jsonObject.put(entry.getKey(), dataMap.get(entry.getKey()));
            }
        }
        //原文书内容没有的字段处理
        for (Map.Entry<String, Object> entry : dataMap.entrySet()) {
            if (!jsonObject.containsKey(entry) && ObjectUtil.isNotEmpty(dataMap.get(entry.getKey()))) {
                jsonObject.put(entry.getKey(), dataMap.get(entry.getKey()));
            }
        }

        CaseDocumentRecord modifyDocument = new CaseDocumentRecord();
        BeanUtils.copyProperties(caseDocumentRecordInfo, modifyDocument);
        //修改文书需要审批，清除审批信息
        if (Constant.STRING_1.equals(saveDto.getIsNeedApproval())) {
            modifyDocument.setDocumentRecordStatus(DocumentRecordStatusEnum.MODIFY.getCode());
            modifyDocument.setDocumentUrlAfterSeal(caseDocumentRecordInfo.getDocumentUrl());
            modifyDocument.setDocumentApprovalStatus(DocumentStatusEnum.WAIT_TO_SUBMIT.getCode());
            modifyDocument.setDocumentApprovalTime(null);
            modifyDocument.setSentDeadline(null);
            modifyDocument.setDocumentUrlAfterSign("");
            modifyDocument.setDocumentSentStatus("");
            modifyDocument.setDocumentSignstampedStatus("");
            modifyDocument.setDocumentSentStatus(null);
            //jsonObject = this.clearApprovalOpinion(jsonObject);
        } else {
            modifyDocument.setDocumentRecordStatus(DocumentRecordStatusEnum.NORMAL.getCode());
            //查询文书配置表
            ConfigBusiParamDocumentInfo configBusiParamDocumentInfo = configBusiParamDocumentInfoService.getDetailByDocumentCatalogCode(caseDocumentRecordInfo.getDocumentCatalogCode());
            //只有调查终结报告更新对应字段
            if (DocumentKindEnum.DOC_KIND_ZJBG.getCode().equals(configBusiParamDocumentInfo.getDocumentKindCode())) {
                //不需要审批则直接作废原文书，更新字段信息
                List<CaseDocumentModifyColumnSaveDto> caseDocumentModifyColumnList = saveDto.getModifyColumnList();
                // 更新文书字段
                CaseDocumentRecordVo caseDocumentRecordVo = new CaseDocumentRecordVo();
                BeanUtils.copyProperties(caseDocumentRecordInfo, caseDocumentRecordVo);
                operateBusiTableByDocumentCatalogCode(caseDocumentModifyColumnList, caseDocumentRecordVo);
            }
            CaseDocumentRecord updateRecord = new CaseDocumentRecord();
            updateRecord.setId(originalDocument);
            updateRecord.setDocumentRecordStatus(DocumentRecordStatusEnum.WITHDRAW.getCode());
            caseDocumentRecordMapper.updateByPrimaryKeySelective(updateRecord);
            //审批表修改但是未审批 发送浙政钉消息
            try {
                System.out.println("ding消息开始-------------");
                CaseMainInfo caseMainInfo = caseMainInfoMapper.selectByPrimaryKey(saveDto.getCaseId());
                //审批表
                List<String> needSendDingMsgKindCode = new ArrayList<>();
                needSendDingMsgKindCode.add(DocumentKindEnum.DOC_KIND_CFGZSPB.getCode());
                needSendDingMsgKindCode.add(DocumentKindEnum.DOC_KIND_LASPB.getCode());
                needSendDingMsgKindCode.add(DocumentKindEnum.DOC_KIND_CFJDSPB.getCode());
                needSendDingMsgKindCode.add(DocumentKindEnum.DOC_KIND_XZCFCXSPB.getCode());
                needSendDingMsgKindCode.add(DocumentKindEnum.DOC_KIND_BYCFJDSPB.getCode());
                if (needSendDingMsgKindCode.contains(configBusiParamDocumentInfo.getDocumentKindCode())) {
                    //查询最新的审批完成记录
                    Example example = new Example(CaseApprovalCompleteRecord.class);
                    if (!Constant.STRING_2.equals(caseMainInfo.getHandleType())) {
                        example.createCriteria().andEqualTo("caseId", caseMainInfo.getId()).andEqualTo("documentId", saveDto.getDocumentCatalogCode());
                    } else {
                        example.createCriteria().andEqualTo("caseId", caseMainInfo.getId()).andEqualTo("documentId", saveDto.getDocumentCatalogCode()).andEqualTo("partyId", caseDocumentRecordInfo.getPartyId());
                    }
                    example.setOrderByClause("approval_time desc");
                    PageHelper.startPage(Constant.INTEGER_1, Constant.INTEGER_3);
                    List<CaseApprovalCompleteRecord> caseApprovalCompleteRecordList = caseApprovalCompleteRecordMapper.selectByExample(example);
                    for (CaseApprovalCompleteRecord caseApprovalCompleteRecord : caseApprovalCompleteRecordList) {
                        if (AuditStatusConstant.AUDIT_STATUS_WAIT.equals(caseApprovalCompleteRecord.getApprovalStatus())) {
                            continue;
                        }
                        List<String> userIds = new ArrayList<>();
                        userIds.add(caseApprovalCompleteRecord.getApprovalUserId());
                        List<ZfAndManageUserInfoVO> list = xzzfInterfaceService.getZfAndManageUsersByUserIds(userIds);
                        for (ZfAndManageUserInfoVO user : list) {
                            System.out.println("ZwdingAccountId-------------" + user.getZwdingAccountId());
                            if (StringUtils.isNotBlank(user.getZwdingAccountId())) {
                                sendModifyDingMsg(caseMainInfo.getCaseNumber(), userInfo.getRealName(), configBusiParamDocumentInfo.getDocumentKindName(), user.getZwdingAccountId());
                            }

                    }
                }

                }
            } catch (Exception e) {
                e.printStackTrace();
                log.info("发送ding消息异常：" + e.getMessage());
            }
        }
        //新增一条文书记录
        String modifyDocumentId = BaseUtil.createUid();
        modifyDocument.setId(modifyDocumentId);
        modifyDocument.setIsModifyRecord(Constant.STRING_1);
        modifyDocument.setDocumentContent(jsonObject.toString());
        // modifyDocument.setDocumentCreateTime(LocalDateTime.now());
        modifyDocument.setCreateUserId(userInfo.getUserId() + "");
        modifyDocument.setCreateUserName(userInfo.getRealName());
        caseDocumentRecordMapper.insertSelective(modifyDocument);
        //3、重新生成文书
        Map<String, Object> paramJson = new HashMap<>(8);

        RebuildDocumentDto dto = new RebuildDocumentDto(modifyDocumentId, "");
        List<RebuildDocumentDto> list = new ArrayList<>();
        list.add(dto);
        paramJson.put("documentInfo", list);
        Result<Map<String, Object>> result = stageDocCommonOperateService.rebuildPdf(paramJson);
        log.info("edit document,rebuild result :{}", result);
        int num = 0;
        if (ObjectUtil.isNotEmpty(result) && HttpStatus.HTTP_OK == result.getCode()) {
            num = (int) result.getData().get("num");
        }
        DocumentRecordModifyReturnVo vo = new DocumentRecordModifyReturnVo();
        if (num > 0) {
            String documentUrlBeforeModify = ObjectUtil.isNotEmpty(caseDocumentRecordInfo.getDocumentUrlAfterSeal()) ? caseDocumentRecordInfo.getDocumentUrlAfterSeal() : caseDocumentRecordInfo.getDocumentUrl();
            vo.setDocumentUrlBeforeModify(documentUrlBeforeModify);
            vo.setCaseId(caseId);
            vo.setDocumentCatalogCode(saveDto.getDocumentCatalogCode());
            CaseDocumentRecordVo documentInfoAfterModify = this.getCaseDocumentRecordInfo(modifyDocumentId);
            String documentUrlAfterModify = ObjectUtil.isNotEmpty(documentInfoAfterModify.getDocumentUrlAfterSeal()) ? documentInfoAfterModify.getDocumentUrlAfterSeal() : documentInfoAfterModify.getDocumentUrl();
            vo.setDocumentUrlAfterModify(documentUrlAfterModify);
            vo.setDocumentIdAfterModify(modifyDocumentId);
            return vo;
        } else {
            throw new BusinessException("修改文书失败,重新生成文书有误");
        }


    }

    /**
     * 发送文书修改ding 消息
     *
     * @param caseNumber
     * @param realName
     * @param documentKindName
     * @return
     * @author liyafeng
     * @date 2023/2/28
     */
    private void sendModifyDingMsg(String caseNumber, String realName, String documentKindName, String zwdingAccountId) {
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("caseNumber", caseNumber);
        jsonObject.put("documentCatalogName", documentKindName);
        jsonObject.put("dingDingId", zwdingAccountId);
        jsonObject.put("name", realName);
        jsonObject.put("dingMsgType", "docModify");
        System.out.println("dingSendUrl-------------" + dingSendUrl);
        BaseUtil.post(dingSendUrl, jsonObject);
    }

    @Override
    public int modifyDocumentRecordAfterApproval(String modifyDocumentId) {
        //查询当前文书对应的修改记录
        CaseDocumentModifyRecord caseDocumentModifyRecord = caseDocumentModifyRecordService.getCaseDocumentModifyRecordByDocumentId(modifyDocumentId);
        CaseDocumentRecordVo modifyDocumentRecord = caseDocumentRecordService.getCaseDocumentRecordInfo(modifyDocumentId);
        ConfigBusiParamDocumentInfo configBusiParamDocumentInfo = configBusiParamDocumentInfoService.getDetailByDocumentCatalogCode(modifyDocumentRecord.getDocumentCatalogCode());
        if (DocumentKindEnum.DOC_KIND_LASPB.getCode().equals(configBusiParamDocumentInfo.getDocumentKindCode())) {
            // 立案文书更新立案信息
            CaseRegisterSaveDto saveDto = JSON.parseObject(modifyDocumentRecord.getDocumentContent(), CaseRegisterSaveDto.class);
            caseRegisterService.modifyCaseRegisterInfo(saveDto);
        }
        //更新修改记录的修改后文书url及审批通过时间
        caseDocumentModifyRecord.setDocumentUrlAfterModify(modifyDocumentRecord.getDocumentUrlAfterSeal());
        if (!ObjectUtils.isEmpty(modifyDocumentRecord.getDocumentApprovalTime())) {
            caseDocumentModifyRecord.setApprovalTime(DateUtil.localDateTimeToDate(modifyDocumentRecord.getDocumentApprovalTime()));
        }
        caseDocumentModifyRecordMapper.updateByPrimaryKey(caseDocumentModifyRecord);
        //作废原文书
        //查询原文书
        CaseDocumentRecord originalDocumentRecord = caseDocumentRecordMapper.selectByPrimaryKey(caseDocumentModifyRecord.getOriginalDocumentId());
        //CaseDocumentRecord originalDocumentRecord= new CaseDocumentRecord();
        originalDocumentRecord.setId(caseDocumentModifyRecord.getOriginalDocumentId());
        originalDocumentRecord.setDocumentRecordStatus(DocumentRecordStatusEnum.WITHDRAW.getCode());
        caseDocumentRecordMapper.updateByPrimaryKeySelective(originalDocumentRecord);
        if (DocumentKindEnum.DOC_KIND_LASPB.getCode().equals(configBusiParamDocumentInfo.getDocumentKindCode())
                || DocumentKindEnum.DOC_KIND_ZJBG.getCode().equals(configBusiParamDocumentInfo.getDocumentKindCode())) {
            // 更新文书字段
            String modifyColumnContent = caseDocumentModifyRecord.getModifyColumnContent();
            List<CaseDocumentModifyColumnSaveDto> caseDocumentModifyColumnList = JSON.parseArray(modifyColumnContent, CaseDocumentModifyColumnSaveDto.class);
            operateBusiTableByDocumentCatalogCode(caseDocumentModifyColumnList, modifyDocumentRecord);
        }
        //更新修改后的文书
        CaseDocumentRecord updateModifyDocumentRecord = new CaseDocumentRecord();
        updateModifyDocumentRecord.setId(modifyDocumentId);
        updateModifyDocumentRecord.setDocumentRecordStatus(DocumentRecordStatusEnum.NORMAL.getCode());

        //更新状态与原文书一致
        if (YesOrNoEnum.YES.getCode().equals(configBusiParamDocumentInfo.getIsSend())) {
            updateModifyDocumentRecord.setDocumentSentStatus(
                    ObjectUtils.isEmpty(originalDocumentRecord.getDocumentSentStatus()) ? DocumentStatusEnum.WAIT_TO_SEND.getCode() : originalDocumentRecord.getDocumentSentStatus());
            updateModifyDocumentRecord.setSentDeadline(originalDocumentRecord.getSentDeadline());
        }
        if (BusinessContextUtil.documentNeedConfirm(configBusiParamDocumentInfo)) {
            updateModifyDocumentRecord.setDocumentSignstampedStatus(
                    ObjectUtils.isEmpty(originalDocumentRecord.getDocumentSignstampedStatus()) ? DocumentStatusEnum.WAIT_TO_CONFIRM.getCode() : originalDocumentRecord.getDocumentSignstampedStatus());
        }
        return caseDocumentRecordMapper.updateByPrimaryKeySelective(updateModifyDocumentRecord);
    }

    /**
     * 获取文书记录列表
     *
     * @param caseId          案件id
     * @param catalogCodeList 文书目录编码列表
     * @return 文书记录列表
     * @author lilihao
     * @date 2023/2/7 14:45
     */
    @Override
    public List<CaseDocumentRecord> getDocumentRecordList(String caseId, List<String> catalogCodeList) {
        //1.获取文书记录列表
        Example example = new Example(CaseDocumentRecord.class);
        example.createCriteria().andEqualTo("caseId", caseId)
                .andEqualTo("documentRecordStatus", YesOrNoEnum.YES.getCode())
                .andIn("documentCatalogCode", catalogCodeList);
        List<CaseDocumentRecord> list = caseDocumentRecordMapper.selectByExample(example);
        return list;
    }

    /**
     * 修改文书内容/链接
     *
     * @param id              文书id
     * @param documentContent 文书内容
     * @param documentUrl     文书链接
     * @return
     * @author lilihao
     * @date 2023/2/7 19:18
     */
    @Override
    public int modifyDocumentContent(String id, String documentContent, String documentUrl) {
        CaseDocumentRecord caseDocumentRecord1 = caseDocumentRecordMapper.selectByPrimaryKey(id);
        CaseDocumentRecord caseDocumentRecord = new CaseDocumentRecord();
        caseDocumentRecord.setId(id);
        caseDocumentRecord.setDocumentContent(documentContent);
        if (StrUtil.isNotBlank(caseDocumentRecord1.getDocumentUrlAfterSeal())) {
            caseDocumentRecord.setDocumentUrlAfterSeal(documentUrl);
        } else {
            caseDocumentRecord.setDocumentUrl(documentUrl);
        }
        return caseDocumentRecordMapper.updateByPrimaryKeySelective(caseDocumentRecord);
    }

    /**
     * 根据配置更新相关数据
     *
     * @param caseDocumentModifyColumnList 用例文档修改列列表
     * @param caseDocumentRecordInfo       用例文档记录信息
     * @author shishengyao
     * @date 2023/01/07
     */
    private void operateBusiTableByDocumentCatalogCode(List<CaseDocumentModifyColumnSaveDto> caseDocumentModifyColumnList, CaseDocumentRecordVo caseDocumentRecordInfo) {
        List<BusiTableOperateVo> busiTableOperateVoList = configBusiParamDocumentColumnMapper.selectTableNameListByDocumentCatalogCode(caseDocumentRecordInfo.getDocumentCatalogCode());
        if (null != busiTableOperateVoList && busiTableOperateVoList.size() > 0) {
            for (CaseDocumentModifyColumnSaveDto caseDocumentModifyColumnSaveDto : caseDocumentModifyColumnList) {
                for (BusiTableOperateVo busiTableOperateVo : busiTableOperateVoList) {
                    String modifyColumn = caseDocumentModifyColumnSaveDto.getModifyColumn();
                    if (modifyColumn.equals(busiTableOperateVo.getDocumentTemplateFieldEn())) {
                        Example example = new Example(ConfigBusiParamDocumentColumn.class);
                        example.createCriteria().andEqualTo("documentCatalogCode", caseDocumentRecordInfo.getDocumentCatalogCode())
                                .andEqualTo("documentTemplateFieldEn", modifyColumn);
                        List<ConfigBusiParamDocumentColumn> configBusiParamDocumentColumnList = configBusiParamDocumentColumnMapper.selectByExample(example);
                        this.updateBusiTable(caseDocumentRecordInfo, caseDocumentModifyColumnSaveDto, busiTableOperateVo, configBusiParamDocumentColumnList);
                    }
                }
            }
        }
    }

    /**
     * 更新操作
     *
     * @param caseDocumentRecordInfo            用例文档记录信息
     * @param caseDocumentModifyColumnSaveDto   用例文档修改列保存dto
     * @param busiTableOperateVo
     * @param configBusiParamDocumentColumnList
     * @author shishengyao
     * @date 2023/01/07
     */
    public void updateBusiTable(CaseDocumentRecordVo caseDocumentRecordInfo, CaseDocumentModifyColumnSaveDto caseDocumentModifyColumnSaveDto, BusiTableOperateVo busiTableOperateVo, List<ConfigBusiParamDocumentColumn> configBusiParamDocumentColumnList) {
        String tableName = busiTableOperateVo.getBusiTableNameEn();
        String caseId = caseDocumentRecordInfo.getCaseId();
        String setSql = "";
        String sqlCondition = "";
        for (ConfigBusiParamDocumentColumn configBusiParamDocumentColumn : configBusiParamDocumentColumnList) {
            //BusiOperateCondition 不为空 此字段不更新
            if (StringUtils.isNotBlank(configBusiParamDocumentColumn.getBusiOperateCondition())) {
                if ("party_id".equals(configBusiParamDocumentColumn.getBusiOperateCondition())) {
                    sqlCondition += " and party_id = '" + caseDocumentRecordInfo.getPartyId() + "'";
                }
                continue;
            }
            if (ObjectUtil.isNotEmpty(configBusiParamDocumentColumn.getDocumentTemplateType()) && !configBusiParamDocumentColumn.getDocumentTemplateType().contains(DocumentTemplateKindEnum.STANDARD_TEMPLATE.getCode())) {
                continue;
            }
            String columnValue = "";
            try {
                columnValue = caseDocumentModifyColumnSaveDto.getColumnContentAfterModify();
                columnValue = columnValue.replace("'", "''");
            } catch (Exception e) {
                //前端没有传key值，此字段不更新
                if (caseDocumentModifyColumnSaveDto.getColumnContentAfterModify() == null)
                    continue;

                throw new BusinessException(configBusiParamDocumentColumn.getDocumentTemplateFieldCn() + "为空");
            }
            if (StringUtils.isBlank(setSql)) {
                setSql = configBusiParamDocumentColumn.getBusiColumnEn() + "='" + columnValue + "'";
            } else {
                setSql = setSql + "," + configBusiParamDocumentColumn.getBusiColumnEn() + "='" + columnValue + "'";
            }
        }
        String updateSql = "update upcase." + tableName + " set " + setSql + " where " + " case_id='" + caseId + "'";

        ConfigBusiParamDocumentInfo configBusiParamDocumentInfo = configBusiParamDocumentInfoService.getDetailByDocumentCatalogCode(caseDocumentRecordInfo.getDocumentCatalogCode());
        if (Constant.STRING_KIND_CODE_SDDZQRS.equals(configBusiParamDocumentInfo.getDocumentKindCode())) {
            updateSql = updateSql.concat(" and party_id = '" + caseDocumentRecordInfo.getPartyId() + "'");
        }
        //案件操作文书
        if (CaseStatusChangeTypeEnum.isCaseChangeDocEnum(configBusiParamDocumentInfo.getDocumentKindCode())) {
            updateSql = updateSql.concat(" and case_change_type = '" + CaseStatusChangeTypeEnum.getEnumByDocumentKindCode(configBusiParamDocumentInfo.getDocumentKindCode()).getCode() + "'");
        }
        updateSql = updateSql.concat(sqlCondition);
        configBusiParamDocumentColumnMapper.executeUpdateSql(updateSql);
    }

    /**
     * 描述：清空审批意见
     *
     * @param dataMap 数据地图
     * @return {@link HashMap<String, Object> }
     * @author shishengyao
     * @date 2023/01/07
     */
    private JSONObject clearApprovalOpinion(JSONObject dataMap) {
        JSONObject jsonMap = new JSONObject();
        for (Map.Entry<String, Object> entry : dataMap.entrySet()) {
            jsonMap.put(entry.getKey(), entry.getValue());
        }
        for (OpinionType ot : OpinionType.values()) {
            jsonMap.put(ot.getAuditUserIdCode(), "");
            jsonMap.put(ot.getDocCode(), "");
            jsonMap.put(ot.getAuditTimeCode(), "");
        }
        return jsonMap;
    }

    /**
     * orgCode处理
     *
     * @param caseDto
     * @return void
     * @author lxj
     * @date 2022/3/31
     **/
    private void checkOrgCode(CaseDocumentPageDto caseDto) {
        caseDto.setOrg(0);
        if (StrUtil.isBlank(caseDto.getOrgCode())) {
            return;
        }
        List<String> orgCodeList = new ArrayList<>();
        List<String> deptCodeList = new ArrayList<>();
        String[] str = caseDto.getOrgCode().split(",");

        for (String s : str) {
            if (s.indexOf("_") > 0) {
                orgCodeList.add(s);
            } else {
                deptCodeList.add(s);
            }
        }
        if (orgCodeList.size() > 0 && deptCodeList.size() > 0) {
            caseDto.setOrg(1);
        } else if (orgCodeList.size() > 0) {
            caseDto.setOrg(2);
        } else if (deptCodeList.size() > 0) {
            caseDto.setOrg(3);
        }

        caseDto.setOrgCodeList(orgCodeList);
        caseDto.setDeptCodeList(deptCodeList);
    }

    /**
     * 【V1.11.0】描述： 获取关联文书记录
     *
     * @return {@link CaseDocumentRecord}
     * @author: zhengqiang
     * @date: 2023/2/24
     * @param: caseId
     * @param: documentCatalogCode
     * @param: relationApprovalDocumentId
     **/
    @Override
    public CaseDocumentRecord getRelationCaseDocumentRecord(String caseId, String documentCatalogCode, String relationApprovalDocumentId) {
        //查询文书记录数据
        Example example = new Example(CaseDocumentRecord.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("caseId", caseId).andEqualTo("documentCatalogCode", documentCatalogCode)
                .andEqualTo("relationApprovalDocumentId", relationApprovalDocumentId)
                .andIn("documentRecordStatus", Arrays.asList(DocumentRecordStatusEnum.NORMAL.getCode(), DocumentRecordStatusEnum.DRAFT.getCode()));
        List<CaseDocumentRecord> caseDocumentRecordList = caseDocumentRecordMapper.selectByExample(example);
        if (caseDocumentRecordList == null || caseDocumentRecordList.size() == 0) {
            return null;
        }
        return caseDocumentRecordList.get(0);
    }

    /**
     * 【V1.11.0】描述： 获取关联文书记录
     *
     * @return {@link CaseDocumentRecord}
     * @param: caseId
     * @param: relationDocumentId
     **/
    @Override
    public CaseDocumentRecord getRelationCaseDocumentRecord(String caseId, String relationDocumentId) {
        //查询文书记录数据
        Example example = new Example(CaseDocumentRecord.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("caseId", caseId)
                .andEqualTo("relationDocumentId", relationDocumentId)
                .andIn("documentRecordStatus", Arrays.asList(DocumentRecordStatusEnum.NORMAL.getCode(), DocumentRecordStatusEnum.DRAFT.getCode()));
        List<CaseDocumentRecord> caseDocumentRecordList = caseDocumentRecordMapper.selectByExample(example);
        if (caseDocumentRecordList == null || caseDocumentRecordList.size() == 0) {
            return null;
        }
        return caseDocumentRecordList.get(0);
    }

    /**
     * 根据stageCode，查询文书列表
     *
     * @param caseId
     * @param stageCode
     * @return
     */
    @Override
    public List<CaseDocumentRecordCodeNameVo> getCaseDocumentRecordByStageCode(String caseId, String stageCode, String busiParamId) {
        return caseDocumentRecordMapper.getCaseDocumentRecordByStageCode(caseId, stageCode, busiParamId);
    }

    /**
     * 【AJ-V1.1.1】描述： 转普通程序文书相关数据处理
     *
     * @return
     * @author: zhengqiang
     * @date: 2023/3/10
     * @param: caseId
     **/
    @Override
    public void dealCaseDocumentRecordOfChangeWorkFlow(String caseId) {
        CaseMainInfoVo caseMainInfo = caseMainInfoService.getCaseMainInfo(caseId);
        ConfigBusiParamDocumentInfo documentInfo = configBusiParamDocumentInfoService.getDocumentInfoByDocumentKindCode(caseMainInfo.getBusiParamId(), DocumentKindEnum.DOC_KIND_LASPB.getCode());
        //作废立案阶段除立案审批表之外的文书
        caseDocumentRecordMapper.updateCaseDocumentRecordOfChangeWorkFlow(caseId, CaseStageEnum.CASE_REGISTER.getCode(), Arrays.asList(documentInfo.getDocumentCatalogCode()));
        //作废调查取证非关联文书
        caseDocumentRecordMapper.updateCaseDocumentRecordOfChangeWorkFlow(caseId, CaseStageEnum.INVESTIGATION.getCode(), null);
        //修改立案审批表工作流环节编码
        ConfigWorkFlowDetailInfo configWorkFlowDetailInfoStart = configWorkFlowDetailInfoService.getConfigWorkFlowDetailInfoStartByFlowCode(caseMainInfo.getCaseFlowCode(), caseMainInfo.getCaseFlowVersion());
        Example updateExample = new Example(CaseDocumentRecord.class);
        updateExample.createCriteria().andEqualTo("caseId", caseId)
                .andEqualTo("documentCatalogCode", documentInfo.getDocumentCatalogCode())
                .andEqualTo("documentRecordStatus", DocumentRecordStatusEnum.NORMAL.getCode());
        CaseDocumentRecord caseDocumentRecordUpdate = new CaseDocumentRecord();
        caseDocumentRecordUpdate.setCaseLinkCode(configWorkFlowDetailInfoStart.getWorkLinkCode());
        caseDocumentRecordMapper.updateByExampleSelective(caseDocumentRecordUpdate, updateExample);
    }

    /**
     * 获取速结告知书
     *
     * @param caseId
     * @return
     */
    public List<CaseDocumentRecord> getCaseDocumentRecordOfSJCXGZS(String caseId) {
        CaseMainInfoVo caseMainInfo = caseMainInfoService.getCaseMainInfo(caseId);
        //获取速结或快办告知书目录编号
        String documentCatalogCodeOfSJGZS = getDocumentCatalogCodeOfSJGZS(caseMainInfo.getCaseAreaCode(), caseMainInfo.getBusiParamId());
        Example example = new Example(CaseDocumentRecord.class);
        example.createCriteria().andEqualTo("caseId", caseId)
                .andEqualTo("documentCatalogCode", documentCatalogCodeOfSJGZS)
                .andEqualTo("documentRecordStatus", DocumentRecordStatusEnum.NORMAL.getCode())
                .andEqualTo("documentSignstampedStatus", DocumentStatusEnum.CONFIRM_END.getCode());
        List<CaseDocumentRecord> caseDocumentRecords = caseDocumentRecordMapper.selectByExample(example);
        return caseDocumentRecords;
    }

    @Override
    public int updateWithdrawCaseDocumentRecordForAdjust(String caseId) {
        CaseMainInfoVo caseMainInfo = caseMainInfoService.getCaseMainInfo(caseId);
        //查询终结报告、案件处理意见书对应的文书目录编码
        Example example = new Example(ConfigBusiParamDocumentInfo.class);
        example.createCriteria().andEqualTo("busiParamId", caseMainInfo.getBusiParamId())
                .andIn("documentKindCode", Arrays.asList(DocumentKindEnum.DOC_KIND_ZJBG.getCode(),
                        DocumentKindEnum.DOC_KIND_DK1AJDCZJBGSPB.getCode(),
                        DocumentKindEnum.DOC_KIND_DK1AJCLYJS.getCode()));
        List<ConfigBusiParamDocumentInfo> configBusiParamDocumentInfos = configBusiParamDocumentInfoMapper.selectByExample(example);
        List<String> documentCatalogCodeList = configBusiParamDocumentInfos.stream().filter(e -> e.getDocumentCatalogCode() != null).map(e -> e.getDocumentCatalogCode()).collect(Collectors.toList());
        //更新文书记录
        Example updateExample = new Example(CaseDocumentRecord.class);
        updateExample.createCriteria().andEqualTo("caseId", caseId)
                .andIn("documentCatalogCode", documentCatalogCodeList)
                .andIn("documentRecordStatus", Arrays.asList(DocumentRecordStatusEnum.NORMAL.getCode(), DocumentRecordStatusEnum.DRAFT.getCode()));
        CaseDocumentRecord caseDocumentRecord = new CaseDocumentRecord();
        caseDocumentRecord.setDocumentRecordStatus(DocumentRecordStatusEnum.WITHDRAW.getCode());
        return caseDocumentRecordMapper.updateByExampleSelective(caseDocumentRecord, updateExample);
    }

    @Override
    public int saveInvalidCaseDocumentRecordByPartyIdForAdjust(String caseId, String partyId) {
        //使非立案阶段的文书失效
        Example updateExample = new Example(CaseDocumentRecord.class);
        updateExample.createCriteria().andEqualTo("caseId", caseId)
                .andEqualTo("partyId", partyId)
                .andIn("documentRecordStatus", Arrays.asList(DocumentRecordStatusEnum.NORMAL.getCode(), DocumentRecordStatusEnum.DRAFT.getCode()))
                .andNotEqualTo("caseStageCode", CaseStageEnum.CASE_REGISTER.getCode());
        CaseDocumentRecord caseDocumentRecord = new CaseDocumentRecord();
        caseDocumentRecord.setDocumentRecordStatus(DocumentRecordStatusEnum.INVALID.getCode());
        return caseDocumentRecordMapper.updateByExampleSelective(caseDocumentRecord, updateExample);
    }

    @Override
    public List<CaseDocumentRecord> getCaseDocumentRecordListByCaseId(String caseId) {
        //1.获取文书记录列表
        Example example = new Example(CaseDocumentRecord.class);
        example.createCriteria().andEqualTo("caseId", caseId)
                .andEqualTo("documentRecordStatus", YesOrNoEnum.YES.getCode());
        List<CaseDocumentRecord> list = caseDocumentRecordMapper.selectByExample(example);
        return list;
    }

    /**
     * 【V1.11.4】描述： 根据区划获取速结或快办告知书目录编码
     *
     * @return {@link String}
     * @author: zhengqiang
     * @date: 2023/4/19
     * @param: areaCode
     * @param: busiParamId
     **/
    @Override
    public String getDocumentCatalogCodeOfSJGZS(String areaCode, String busiParamId) {
        String kindCode = null;
        //根据区划判断生成安吉速结告知书还是简案快办通知书
        if (areaCode.contains(Constant.STRING_AREA_CODE_ANJI)) {
            //安吉则生成安吉速结告知书
            kindCode = DocumentKindEnum.DOC_KIND_DK2SJCXGZS.getCode();
        } else {
            kindCode = DocumentKindEnum.DOC_KIND_DK2JAKBTZS.getCode();
        }
        // 查询业务关联文书配置
        ConfigBusiParamDocumentInfo configBusiParam = configBusiParamDocumentInfoService.getDocumentInfoByDocumentKindCode(busiParamId, kindCode);
        if (Objects.isNull(configBusiParam)) {
            throw new BusinessException("业务关联文书配置不存在");
        }
        return configBusiParam.getDocumentCatalogCode();
    }

    /**
     * 简案快办修改文书
     *
     * @param dto
     * @return {@link int}
     * @author liyafeng
     * @date 2023/5/6
     */
    @Override
    public int modFastCaseDocumentRecord(ModFastCaseDocumentRecordDto dto) {
        CaseDocumentRecord updateCaseDocumentRecord = new CaseDocumentRecord();
        updateCaseDocumentRecord.setId(dto.getDocId());
        updateCaseDocumentRecord.setDocumentUrl(dto.getDocUrl());
        updateCaseDocumentRecord.setDocumentContent(JSONObject.toJSON(dto.getDataMap()).toString());
        int updateNum = caseDocumentRecordMapper.updateByPrimaryKeySelective(updateCaseDocumentRecord);
        return updateNum;
    }
}
